1. 程式人生 > >java實現excel的匯出

java實現excel的匯出

java Excel的三種解析

 

1.POI 是apche軟體基金會的開源函式庫 提供api對microsoft office格式檔案讀寫功能

 

2.HSSFF 純java程式碼讀取 寫入 修改 EXcel檔案 (2007以下版本) 還要xssf (對2007以上版本的excel) HWPF等(對word)

 

3.itext.jar 可以生成pdf檔案

 

4. JXL 開源專案 可以對excel進行建立 修改 更新 包括設定字型 顏色 背景等等

 

5.fastExcel 純java開發的excel檔案讀寫元件 支援excel97-2003檔案格式 只能讀取單元格字元資訊 但是隻需要很小的記憶體 效率高

 

 

主要是POI 和JXL

 

 

POI操作效率高 但是操作複雜 支援公式 巨集

 

JXL效率低 但是操作簡單 格式不如POI強大

 

maven引入三方

 

<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->

<dependency>

<groupId>net.sourceforge.jexcelapi</groupId>

<artifactId>jxl</artifactId>

<version>2.6.12</version>

</dependency>

</dependencies>

 

 

//建立工作薄

WritableWorkbook workbook = Workbook.createWorkbook(out);

 

//建立sheet

WritableSheet sheet=workbook.createSheet("sheet1",0);

 

//單元格

Label label=null;

 

//陣列存表頭

String[] title={"id","name","sex"};

 

//設定列名

for(int i=0;i<title.length;i++){

label=new Label(i,0,title[i]);

sheet.addCell(label);

 

}

 

for(int i=1;i<10;i++){

//第一列 new Label(0,i,"a"); 0是列 i是行

label =new Label(0,i,"a");

sheet.addCell(label);

//第二列

label =new Label(1,i,"user");

sheet.addCell(label);

//第三列

label =new Label(2,i,"男");

sheet.addCell(label);

 

}

 

//寫入資料

workbook.write();

workbook.close();

 

 

 

如果要訪問url就能下載檔案 那麼返回到要是一個流

 

@GetMapping(value = "excel")

public void excel(HttpServletResponse response) throws IOException, WriteException {

 

response.setContentType("application/octet-stream");

response.setHeader("Content-Disposition", "attachment;filename=car_test.xls");

ServletOutputStream out=response.getOutputStream();

 

 

//建立工作薄

WritableWorkbook workbook = Workbook.createWorkbook(out);

 

//建立sheet

WritableSheet sheet=workbook.createSheet("sheet1",0);

 

//單元格

Label label=null;

 

//陣列存表頭

String[] title={"id","name","sex"};

 

//設定列名

for(int i=0;i<title.length;i++){

label=new Label(i,0,title[i]);

sheet.addCell(label);

 

}

 

for(int i=1;i<10;i++){

//第一列 new Label(0,i,"a"); 0是列 i是行

label =new Label(0,i,"a");

sheet.addCell(label);

//第二列

label =new Label(1,i,"user");

sheet.addCell(label);

//第三列

label =new Label(2,i,"男");

sheet.addCell(label);

 

}

 

//寫入資料

workbook.write();

workbook.close();

out.flush();

out.close();

 

 

}