最近项目需要操作Excel,发现比较热门的方案是JXL和apache POI。简单看了下,JXL支持Excel,看起来比较轻量而且最后更新时间是2009年。最后还是决定用POI来解决,该项目支持所有MS文档格式。POI有几乎所有Apache项目的通病,jar包超大,还好这个没引用那一堆Apache项目的通用包,算是不幸中之大幸。POI项目文档还算比较详细,看完快速入门,基本使用应该就没什么问题了。
最新的POI 3.8
完整的代码见附件!
package readxml;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class writeExcel {
public static void main(String args[]){
try{
//excel 2003
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
// Create a row and put some cells in it. Rows are 0 based.
for(int i=0;i<10;i++){
Row row = sheet1.createRow((short)i);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue("abc");
row.createCell(3).setCellValue(true);
}
wb.write(fileOut);
fileOut.close();
//适用于 2007 xlsx
Workbook wbss = new XSSFWorkbook();
Sheet ss1 = wbss.createSheet("new sheet");
Sheet ss2 = wbss.createSheet("second sheet");
// Create a row and put some cells in it. Rows are 0 based.
for(int i=0;i<10;i++){
Row row = ss1.createRow((short)i);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue("abc");
row.createCell(3).setCellValue(true);
}
FileOutputStream ssfileOut = new FileOutputStream("workbookxlsx.xlsx");
wbss.write(ssfileOut);
fileOut.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
java 操作 读取 写入 excel POI
猜你喜欢
转载自zjutsoft.iteye.com/blog/1472526
今日推荐
周排行