1. 程式人生 > >POI包讀取、編輯EXCEL,xls、xlsx

POI包讀取、編輯EXCEL,xls、xlsx

最近在使用apache poi包的時候,遇到了一些問題。

就是需要讀取xlsx格式的表格時需要匯入xmlbeans包,但是這個包在apache官網上顯示已經被停用了http://attic.apache.org/projects/xmlbeans.html,在apache attic上儲存的存檔版本是1.0.2和1.0.3的版本,不符合poi包的需求。

在國內的網站論壇上,雖然有很多使用poi包讀取excel的例子,但很少有說明關於xmlbeans這個包的情況的,其他包在apache poi網站上下載的資料夾中都有,只有這個包沒有,即使去官網找,也找不到合適的版本,因此我後來去google了一下,下載新版本的xmlbeans確實可以使用。當然,只使用xls格式的excel表格就可以不關注這個問題了。

http://www.java2s.com/Code/Jar/x/Downloadxmlbeans260jar.htm 這是2.6版本的一個下載連結,需要讀取或操作xlsx格式的excel時需要匯入。

附上apache poi網站上的建議生成excel程式碼

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class FileEx {
	@SuppressWarnings({ "deprecation", "static-access"})
	public static void writeExcel() throws IOException{
		Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
		for(int i=0; i<wbs.length; i++) {
		   Workbook wb = wbs[i];
		   CreationHelper createHelper = wb.getCreationHelper();

		   // 建立一頁表
		   Sheet s = wb.createSheet();
		   // 宣告行物件引用
		   @SuppressWarnings("unused")
		   Row r = null;
		   // 宣告列物件引用
		   @SuppressWarnings("unused")
		   Cell c = null;
		   // 建立兩行樣式
		   CellStyle cs = wb.createCellStyle();
		   CellStyle cs2 = wb.createCellStyle();
		   DataFormat df = wb.createDataFormat();

		   // 建立兩個字型物件
		   Font f = wb.createFont();
		   Font f2 = wb.createFont();

		   // Set font 1 to 12 point type, blue and bold
		   f.setFontHeightInPoints((short) 12);
		   f.setColor( IndexedColors.RED.getIndex() );
		   f.setBoldweight(Font.BOLDWEIGHT_BOLD);

		   // Set font 2 to 10 point type, red and bold
		   f2.setFontHeightInPoints((short) 10);
		   f2.setColor( IndexedColors.RED.getIndex() );
		   f2.setBoldweight(Font.BOLDWEIGHT_BOLD);

		   // Set cell style and formatting
		   cs.setFont(f);
		   cs.setDataFormat(df.getFormat("#,##0.0"));

		   // Set the other cell style and formatting
		   cs2.setBorderBottom(cs2.BORDER_THIN);
		   cs2.setDataFormat(df.getFormat("text"));
		   cs2.setFont(f2);


		   // 定義幾行
		   for(int rownum = 0; rownum < 30; rownum++) {
			   Row r1 = s.createRow(rownum);
			   for(int cellnum = 0; cellnum < 10; cellnum += 2) {
				   Cell c1 = r1.createCell(cellnum);
				   Cell c2 = r1.createCell(cellnum+1);
		   
				   c1.setCellValue((double)rownum + (cellnum/10));
				   c2.setCellValue(
				         createHelper.createRichTextString("Hello! " + cellnum)
				   );
			   }
		   }
		   
		   // 儲存
		   String filename = "workbook.xls";
		   if(wb instanceof XSSFWorkbook) {
		     filename = filename + "x";
		   }
		 
		   FileOutputStream out = new FileOutputStream(filename);
		   wb.write(out);
		   out.close();
		}
	}
	public static void main(String[] str) throws IOException{
		writeExcel();
	}
}
建議有英文水品的可以直接參考apache poi 的java doc,上面講述的更加詳細些