1. 程式人生 > >JavaWeb 利用POI實現前端資料到Excel匯出

JavaWeb 利用POI實現前端資料到Excel匯出

需求

我們用Ext的gridPanel完成了如下表格:
這裡寫圖片描述
現在我們需要對前端表格中的資料匯出到本地的Excel格式,如下:
這裡寫圖片描述

實現

1、簡介

Apache POI是Apache軟體基金會的開放原始碼函式庫,POI提供API給Java程式對Microsoft Office格式檔案讀和寫的功能。自2009-09-28後,推出了3.5版本,提供了對Office2007的支援,

關於Apache POI一些重要的地方:
- 1)Apache POI 包含適合Excel97-2007(.xls檔案)的HSSF實現.
- 2)Apache POI XSSF實現用來處理Excel2007檔案(.xlsx).
- 3)Apache POI HSSF和XSSF提供了讀/寫/修改Excel表格的機制.
- 4)Apache POI 提供了XSSF的一個擴充套件SXSSF用來處理非常大的Excel工作單元.SXSSF
API需要更少的記憶體,因此當處理非常大的電子表格同時堆記憶體又有限時,很合適使用.
- 5)有兩種模式可供選擇–事件模式和使用者模式.事件模式要求更少的記憶體,因為用tokens來讀取Excel並處理.使用者模式更加面向物件並且容易使用,因此在我們的示例中使用使用者 模式.
- 6)Apache POI為額外的Excel特性提供了強大支援,例如處理公式,建立單元格樣式–顏色,邊框,字型,頭部,腳部,資料驗證,影象,超連結等.

2、實現步驟

2.1 POI依賴的jar包
2.1.1需要匯入的jar包

  • Poi-3.10-Final.jar (用於xls)
  • Poi-ooxml-3.10-Final.jar (用於xlsx)
  • Poi-ooxml-schemas-3.10.jar
  • Xmlbeans-2.30.jar
  • dom4j-1.6.1.jar
  • poi-scratchpad-3.10-FINAL-20140208.jar(用於word,ppt)

2.1.2maven構建專案
我們只需要在pom.xml寫入依賴

<dependency>
    <groupId>org.apache.poi</groupId
>
<artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency>

2.2controller層的具體實現
service取資料的過程和前端gridpanel獲取資料相同即可

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat
; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.JOptionPane; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.CellRangeAddress; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.salmon.share.entity.dataApplyManager.PipePermissionApply; import com.salmon.share.service.dataApplyManager.DataPermissionApplyService; @RestController @RequestMapping("/exportExcelController") public class PartExportController { @Autowired private DataPermissionApplyService dataPermissionApplyService; //匯出配件列表 @RequestMapping(value = "/exportExcel", method={RequestMethod.POST,RequestMethod.GET}) @ResponseBody public void exportReportStaticsData( HttpServletRequest request, HttpServletResponse response) { String mether =request.getMethod(); //獲取查詢資料,在service層實現 List<PipePermissionApply> list = dataPermissionApplyService.getDataToExportExcel(); HSSFWorkbook wb = new HSSFWorkbook();//宣告工 Sheet sheet = wb.createSheet("資料許可權申請審批表");//新建表 sheet.setDefaultColumnWidth(15);//設定表寬 HSSFCellStyle style = wb.createCellStyle(); org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont(); font.setFontHeightInPoints((short) 12); HSSFCellStyle headerStyle = wb.createCellStyle(); org.apache.poi.hssf.usermodel.HSSFFont headerFont = wb.createFont(); headerFont.setFontHeightInPoints((short) 14); headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); headerStyle.setFont(headerFont); CellRangeAddress cra0 = new CellRangeAddress(0, 1,0,9); sheet.addMergedRegion(cra0); sheet.setDefaultColumnWidth((short) 15); Row row = sheet.createRow(0); Cell cell1 = row.createCell(0); cell1.setCellValue("資料許可權申請審批表"); cell1.setCellStyle(headerStyle); //設定字型樣式 org.apache.poi.hssf.usermodel.HSSFFont titleFont = wb.createFont(); titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setFont(titleFont); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); Row row1 = sheet.createRow(2); Cell cell = row1.createCell(0); cell.setCellValue("申請流水號"); cell.setCellStyle(style); cell = row1.createCell(1); cell.setCellValue("申請事由"); cell.setCellStyle(style); cell = row1.createCell(2); cell.setCellValue("申請人"); cell.setCellStyle(style); cell = row1.createCell(3); cell.setCellValue("提交時間"); cell.setCellStyle(style); cell = row1.createCell(4); cell.setCellValue("開始時間"); cell.setCellStyle(style); cell = row1.createCell(5); cell.setCellValue("到期時間"); cell.setCellStyle(style); cell = row1.createCell(6); cell.setCellValue("審批人"); cell.setCellStyle(style); cell = row1.createCell(7); cell.setCellValue("審批時間"); cell.setCellStyle(style); // cell = row1.createCell(8); // cell.setCellValue("最小值"); // cell = row1.createCell(9); // cell.setCellValue("最小值時間"); // cell.setCellStyle(style); //時間轉字串的格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0, imax = list.size(); i < imax; i++) { row1 = sheet.createRow(i + 3); if (list.get(i).getCode()== null||"".equals(list.get(i).getCode())) { row1.createCell(0).setCellValue("-"); } else { row1.createCell(0).setCellValue(list.get(i).getCode()); } if (list.get(i).getApply_reason() == null ||"".equals(list.get(i).getApply_reason())) { row1.createCell(1).setCellValue("-"); } else { row1.createCell(1).setCellValue(list.get(i).getApply_reason()); } if (list.get(i).getApply_user_name() == null ||"".equals(list.get(i).getApply_user_name())) { row1.createCell(2).setCellValue("-"); } else { row1.createCell(2).setCellValue(list.get(i).getApply_user_name()); } if (list.get(i).getSubmit_time() == null||"".equals(list.get(i).getSubmit_time())) { row1.createCell(3).setCellValue("-"); } else { row1.createCell(3).setCellValue(sdf.format(list.get(i).getSubmit_time())); } if (list.get(i).getStart_time() == null||"".equals(list.get(i).getStart_time())) { row1.createCell(4).setCellValue("-"); } else { row1.createCell(4).setCellValue(sdf.format(list.get(i).getStart_time())); } if (list.get(i).getEnd_time() == null||"".equals(list.get(i).getEnd_time())) { row1.createCell(5).setCellValue("-"); } else { row1.createCell(5).setCellValue(sdf.format(list.get(i).getEnd_time())); } if (list.get(i).getApproval_user_name() == null||"".equals(list.get(i).getApproval_user_name())) { row1.createCell(6).setCellValue("-"); } else { row1.createCell(6).setCellValue(list.get(i).getApproval_user_name()); } if (list.get(i).getApproval_time() == null||"".equals(list.get(i).getApproval_time())) { row1.createCell(7).setCellValue("-"); } else { row1.createCell(7).setCellValue(sdf.format(list.get(i).getApproval_time())); } } response.reset(); response.setContentType("application/msexcel;charset=UTF-8"); try { SimpleDateFormat newsdf=new SimpleDateFormat("yyyyMMddHHmmss"); String date = newsdf.format(new Date()); response.addHeader("Content-Disposition", "attachment;filename=\"" + new String(("資料許可權申請審批表" + date + ".xls").getBytes("GBK"), "ISO8859_1") + "\""); OutputStream out = response.getOutputStream(); wb.write(out); out.flush(); out.close(); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "匯出失敗!"); e.printStackTrace(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "匯出失敗!"); e.printStackTrace(); } } }

2.3前臺呼叫
我們在前臺設定一個按鈕,在按鈕點選觸發事件中寫

var urlLink = window.loction.href;//獲取當前頁面的連結
var exportLink = urlLink .split("/xxxx")[0];//按照實際情況獲取伺服器連結
exportLink +="/exportExcelController/exportExcel";//拼接controller訪問地址
window.open(exportLink ,'_self');進行訪問

3、拓展–HSSFCellStyle樣式詳解

// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設定這些樣式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中 
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中

 // 背景色
style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
style.setFillBackgroundColor(HSSFColor.YELLOW.index); 

// 設定邊框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
// 自動換行  
style.setWrapText(true);  

// 生成一個字型
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(HSSFColor.RED.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋體");

// 把字型 應用到當前樣式
style.setFont(font);

//style設定好後,為cell設定樣式
cell.setCellStyle(style)//cell為已有的單元格