POI操做EXCEL

Jakarta POI 是一套用於訪問微軟格式文檔的Java API。 
Jakarta POI有不少組件組成,其中有用於操做Excel格式文件的HSSF和用於早在Word的HWPF,在各類組件中目前只有用於操做Excel的HSSF相對成熟。它的官方首頁是:http://jakarta.apache.org/poi/hssf/index.html,這裏能夠下載到它的最新版本和文檔。 
下面就來看看如何經過Jakarta POI的HSSF操做Excel文件。 
操做Excel文件的步驟同JXL相似(關於如何用JXL操做Excel能夠看個人另外兩篇文章)。 
HSSF對Excel的操做主要是經過下面幾個對象實現: 
HSSFWorkbook    工做簿對象對應於Excel文件 
HSSFSheet       Sheet對象對應於Excel中的Sheet 
HSSFRow         行對象表示Sheet中的一行(這個對象在JXL中並無提供) 
HSSFCell        單元格對象 
操做步驟就是用HSSFWorkbook打開或者建立「Excel文件對象」,用HSSFWorkbook對象返回或者建立Sheet對象,用Sheet對象返回行對象,用行對象獲得Cell對象,有了Cell對象就隨你讀寫了。下面來看一個動態生成Excel文件的例子: 
html

//建立HSSFWorkbook對象 
HSSFWorkbook wb = new HSSFWorkbook(); 
//建立HSSFSheet對象 
HSSFSheet sheet = wb.createSheet("sheet0"); 
//建立HSSFRow對象 
HSSFRow row = sheet.createRow((short)0); 
//建立HSSFCell對象 
HSSFCell cell=row.createCell((short)0); 
//用來處理中文問題 
cell.setEncoding(HSSFCell.ENCODING_UTF_16); 
//設置單元格的值 
cell.setCellValue("單元格中的中文"); 
//定義你須要的輸出流 
OutputStream out = new FileOutputStream("viwo.xls"); 
//輸出Excel 
wb.write(out); 
out.flush();

HSSF讀取文件一樣仍是使用這幾個對象,只是把相應的createXXX方法變成了getXXX方法便可。 
只要理解了其中原理,無論是讀仍是寫亦或是特定格式均可以輕鬆實現,正所謂知其然更要知其因此然。

java

1、示例1: apache

package com.cplatform.contants;
import java.io.FileOutputStream;   
import java.io.IOException;   
import java.util.Date;   
import org.apache.poi.hssf.usermodel.HSSFCell;   
import org.apache.poi.hssf.usermodel.HSSFCellStyle;   
import org.apache.poi.hssf.usermodel.HSSFDataFormat;   
import org.apache.poi.hssf.usermodel.HSSFRow;   
import org.apache.poi.hssf.usermodel.HSSFSheet;   
import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
import org.apache.poi.hssf.util.HSSFColor;   
public class A {   
    /** 
     * HSSFWorkbook excell的文檔對象 HSSFSheet excell的表單 HSSFRow excell的行 HSSFCell 
     * excell的格子單元 HSSFFont excell字體 HSSFName 名稱 HSSFDataFormat 日期格式 HSSFHeader 
     * sheet頭 HSSFFooter sheet尾 HSSFCellStyle cell樣式 
     */ 
    public static void main(String[] args) throws IOException {   
        HSSFWorkbook wb = new HSSFWorkbook();   
        // 創建新HSSFWorkbook對象   
        HSSFSheet sheet = wb.createSheet("new sheet");   
        // 創建新的sheet對象   
        // Create a row and put some cells in it.Rows are 0 based.   
        HSSFRow row = sheet.createRow((short) 0);   
        // 創建新行   
        // Create a cell and put a value in it.   
        HSSFCell cell = row.createCell((short) 0);   
        // 創建新cell   
        cell.setCellValue(1);// 設置cell的整數類型的值   
        // Or do it on one line.   
        row.createCell((short) 1).setCellValue(1.2);   
        // 設置cell浮點類型的值   
        row.createCell((short) 2).setCellValue("test");   
        // 設置cell字符類型的值   
        row.createCell((short) 3).setCellValue(true);   
        // 設置cell布爾類型的值   
        HSSFCellStyle cellStyle = wb.createCellStyle();   
        // 創建新的cell樣式   
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));   
        // 設置cell樣式爲定製的日期格式   
        HSSFCell dCell = row.createCell((short) 4);   
        dCell.setCellValue(new Date());   
        // 設置cell爲日期類型的值   
        dCell.setCellStyle(cellStyle);   
        // 設置該cell日期的顯示格式   
        HSSFCell csCell = row.createCell((short) 5);   
        csCell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        // 設置cell編碼解決中文高位字節截斷   
        csCell.setCellValue("中文測試_Chinese Words Test");   
        // 設置背景色   
        HSSFCellStyle style = wb.createCellStyle();   
        style.setFillForegroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());   
        style.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT().getIndex());   
        style.setFillPattern(HSSFCellStyle.SPARSE_DOTS);   
        HSSFCell cell1 = row.createCell((short) 6);   
        cell1.setCellValue("X");   
        cell1.setCellStyle(style);   
        // 設置背景色   
        HSSFCellStyle style1 = wb.createCellStyle();   
        style1.setFillForegroundColor(new HSSFColor.GREY_40_PERCENT().getIndex());   
        style1.setFillBackgroundColor(new HSSFColor.GREY_40_PERCENT().getIndex());   
        style1.setBorderBottom((short) 1);   
        style1.setBorderTop((short) 1);   
        style1.setBorderLeft((short) 1);   
        style1.setBorderRight((short) 1);   
        /** 
         * 注意這句代碼, style1.setFillPattern, 若是你在你的程序中不設置fill pattern,那麼 
         * 你上面設置的前景色和背景色就顯示不出來.
         */ 
        style1.setFillPattern(HSSFCellStyle.SPARSE_DOTS);   
        HSSFCell cell11 = row.createCell((short) 7);   
        cell11.setCellValue("X11");   
        cell11.setCellStyle(style1);   
        // 數字格式化   
        HSSFCellStyle st = wb.createCellStyle();   
        // 創建新的cell樣式   
        st.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0"));   
        HSSFCell cell12 = row.createCell((short) 8);   
        cell12.setCellValue((double) 10000000);   
        cell12.setCellStyle(st);  
        cell12 .setEncoding(HSSFCell.ENCODING_UTF_16);//設置cell編碼解決中文高位字節截斷
        cell12 .setCellValue("中文測試_Chinese Words Test");//設置中西文結合字符串
        row.createCell((short) 9).setCellType(HSSFCell.CELL_TYPE_ERROR);   
        // 創建錯誤cell   
        // Write the output to a file   
        FileOutputStream fileOut = new FileOutputStream("D:/workbook.xls");   
        wb.write(fileOut);   
        fileOut.close();   
    }   
}


2、示例2:測試

package com.cplatform.contants;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/** */
/**
* 生成導出Excel文件對象
* 
* @author John.Zhu
*/
public class XLSExport {
// 設置cell編碼解決中文高位字節截斷
private static short XLS_ENCODING = HSSFWorkbook.ENCODING_UTF_16;
// 定製日期格式
private static String DATE_FORMAT = " m/d/yy "; // "m/d/yy h:mm"
// 定製浮點數格式
private static String NUMBER_FORMAT = " #,##0.00 ";
private String xlsFileName;
private HSSFWorkbook workbook;
private HSSFSheet sheet;
private HSSFRow row;

/**
* 初始化Excel
* @param fileName  導出文件名
*/
public XLSExport(String fileName) {
   this.xlsFileName = fileName;
   this.workbook = new HSSFWorkbook();
   this.sheet = workbook.createSheet();
}

/**
* 導出Excel文件
* @throws XLSException
*/
public void exportXLS() throws Exception {
   try {
    FileOutputStream fOut = new FileOutputStream(xlsFileName);
    workbook.write(fOut);
    fOut.flush();
    fOut.close();
   }
   catch (FileNotFoundException e) {
    throw new Exception(" 生成導出Excel文件出錯! ", e);
   }
   catch (IOException e) {
    throw new Exception(" 寫入Excel文件出錯! ", e);
   }
}

/**
* 增長一行
* @param index  行號
*/
public void createRow(int index) {
   this.row = this.sheet.createRow(index);
}

/**
* 設置單元格
* @param index 列號
* @param value 單元格填充值
*/
public void setCell(int index, String value) {
   HSSFCell cell = this.row.createCell((short) index);
   cell.setCellType(HSSFCell.CELL_TYPE_STRING);
   cell.setEncoding(XLS_ENCODING);
   cell.setCellValue(value);
}

/**
* 設置單元格
* @param index 列號
* @param value 單元格填充值
*/
public void setCell(int index, Calendar value) {
   HSSFCell cell = this.row.createCell((short) index);
   cell.setEncoding(XLS_ENCODING);
   cell.setCellValue(value.getTime());
   HSSFCellStyle cellStyle = workbook.createCellStyle(); // 創建新的cell樣式
   cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(DATE_FORMAT)); // 設置cell樣式爲定製的日期格式
   cell.setCellStyle(cellStyle); // 設置該cell日期的顯示格式
}

/**
* 設置單元格
* @param index 列號
* @param value 單元格填充值
*/
public void setCell(int index, int value) {
   HSSFCell cell = this.row.createCell((short) index);
   cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
   cell.setCellValue(value);
}

/**
* 設置單元格
* @param index 列號
* @param value 單元格填充值
*/
public void setCell(int index, double value) {
   HSSFCell cell = this.row.createCell((short) index);
   cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
   cell.setCellValue(value);
   HSSFCellStyle cellStyle = workbook.createCellStyle(); // 創建新的cell樣式
   HSSFDataFormat format = workbook.createDataFormat();
   cellStyle.setDataFormat(format.getFormat(NUMBER_FORMAT)); // 設置cell樣式爲定製的浮點數格式
   cell.setCellStyle(cellStyle); // 設置該cell浮點數的顯示格式
}
public static void main(String[] args) {
   System.out.println(" 開始導出Excel文件 ");
   XLSExport e = new XLSExport("d:/test.xls");
   e.createRow(0);
   e.setCell(0, " 編號 ");
   e.setCell(1, " 名稱 ");
   e.setCell(2, " 日期 ");
   e.setCell(3, " 金額 ");
   e.createRow(1);
   e.setCell(0, 1);
   e.setCell(1, " 工商銀行 ");
   e.setCell(2, Calendar.getInstance());
   e.setCell(3, 111123.99);
   e.createRow(2);
   e.setCell(0, 2);
   e.setCell(1, " 招商銀行 ");
   e.setCell(2, Calendar.getInstance());
   e.setCell(3, 222456.88);
   try {
    e.exportXLS();
    System.out.println(" 導出Excel文件[成功] ");
   }
   catch (Exception e1) {
    System.out.println(" 導出Excel文件[失敗] ");
    e1.printStackTrace();
   }
}
}
相關文章
相關標籤/搜索