Apache POI使用詳解(看完這篇基本上能應付工作中常用的excel)

本號主要用於分享企業中常用的技術,更加側重於實用,歡迎關注,便於瀏覽其它更多實用的歷史文章。

一 :簡介

開發中經常會設計到excel的處理,如導出Excel,導入Excel到數據庫中,操作Excel目前有兩個框架,一個是apache 的poi, 另一個是 Java Excel

Apache POI 簡介是用Java編寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程式對Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式檔案讀和寫的功能。POI為“Poor Obfuscation Implementation”的首字母縮寫,意為“可憐的模糊實現”。

官方主頁: http://poi.apache.org/index.html

API文檔: http://poi.apache.org/apidocs/index.html

Java Excel是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。jxl 由於其小巧 易用的特點, 逐漸已經取代了 POI-excel的地位, 成為了越來越多的java開發人員生成excel文件的首選。

由於apache poi 在項目中用的比較多,本篇博客只講解apache poi,不講jxl

二:Apache POI常用的類

  • HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能。
  • XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
  • HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能。
  • XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能。
  • HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能。
  • HDGF - 提供讀Microsoft Visio格式檔案的功能。
  • HPBF - 提供讀Microsoft Publisher格式檔案的功能。
  • HSMF - 提供讀Microsoft Outlook格式檔案的功能。

在開發中我們經常使用HSSF用來操作Excel處理表格數據,對於其它的不經常使用。

HSSF 是Horrible SpreadSheet Format的縮寫,通過HSSF,你可以用純Java代碼來讀取、寫入、修改Excel文件。HSSF 為讀取操作提供了兩類API:usermodel和eventusermodel,即“用戶模型”和“事件-用戶模型”。

常用的類和方法

  • HSSFWorkbook :工作簿,代表一個excel的整個文檔
  • HSSFWorkbook();// 創建一個新的工作簿
  • HSSFWorkbook(InputStream inputStream); // 創建一個關聯輸入流的工作簿,可以將一個excel文件封裝成工作簿
  • HSSFSheet createSheet(String sheetname); 創建一個新的Sheet
  • HSSFSheet getSheet(String sheetName); 通過名稱獲取Sheet
  • HSSFSheet getSheetAt(int index); // 通過索引獲取Sheet,索引從0開始
  • HSSFCellStyle createCellStyle(); 創建單元格樣式
  • int getNumberOfSheets(); 獲取sheet的個數
  • setActiveSheet(int index); 設置默認選中的工作表
  • write();
  • write(File newFile);
  • write(OutputStream stream);
  • HSSFSheet:工作表
  • HSSFRow createRow(int rownum); 創建新行,需要指定行號,行號從0開始
  • HSSFRow getRow(int index); 根據索引獲取指定的行
  • int addMergedRegion(CellRangeAddress region); 合併單元格
  • CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol); 單元格範圍, 用於合併單元格,需要指定要合併的首行、最後一行、首列、最後一列。
  • autoSizeColumn(int column); 自動調整列的寬度來適應內容
  • getLastRowNum(); 獲取最後的行的索引,沒有行或者只有一行的時候返回0
  • setColumnWidth(int columnIndex, int width); 設置某一列的寬度,width=字符個數 * 256,例如20個字符的寬度就是20 * 256
  • HSSFRow :行
  • HSSFCell createCell(int column); 創建新的單元格
  • HSSFCell setCell(shot index);
  • HSSFCell getCell(shot index);
  • setRowStyle(HSSFCellStyle style); 設置行樣式
  • short getLastCellNum(); 獲取最後的單元格號,如果單元格有第一個開始算,lastCellNum就是列的個數
  • setHeightInPoints(float height); 設置行的高度
  • HSSFCell:單元格
  • setCellValue(String value); 設置單元格的值
  • setCellType(); 設置單元格類型,如 字符串、數字、布爾等
  • setCellStyle(); 設置單元格樣式
  • String getStringCellValue(); 獲取單元格中的字符串值
  • setCellStyle(HSSFCellStyle style); 設置單元格樣式,例如字體、加粗、格式化
  • setCellFormula(String formula); 設置計算公式,計算的結果作為單元格的值,也提供了異常常用的函數,如求和"sum(A1,C1)"、日期函數、字符串相關函數、CountIf和SumIf函數、隨機數函數等
  • HSSFCellStyle :單元格樣式
  • setFont(Font font); 為單元格設置字體樣式
  • setAlignment(HorizontalAlignment align); // 設置水平對齊方式
  • setVerticalAlignment(VerticalAlignment align); // 設置垂直對齊方式
  • setFillPattern(FillPatternType fp);
  • setFillForegroundColor(short bg); 設置前景色
  • setFillBackgroundColor(short bg); 設置背景顏色
  • HSSFFont:字體,
  • setColor(short color);// 設置字體顏色
  • setBold(boolean bold); // 設置是否粗體
  • setItalic(boolean italic); 設置傾斜
  • setUnderline(byte underline); 設置下劃線
  • HSSFName:名稱
  • HSSFDataFormat :日期格式化
  • HSSFHeader : Sheet的頭部
  • HSSFFooter :Sheet的尾部
  • HSSFDateUtil :日期工具
  • HSSFPrintSetup :打印設置
  • HSSFErrorConstants:錯誤信息表

Excel中的工作簿、工作表、行、單元格中的關係:

  • 一個Excel文件對應於一個workbook(HSSFWorkbook),
  • 一個workbook可以有多個sheet(HSSFSheet)組成,
  • 一個sheet是由多個row(HSSFRow)組成,
  • 一個row是由多個cell(HSSFCell)組成

三:基礎示例

首先引入apache poi的依賴

<code><dependency> 
<groupid>org.apache.poi/<groupid>
<artifactid>poi/<artifactid>
<version>3.8/<version>
/<dependency>/<code>

示例一:在桌面上生成一個Excel文件

<code>public static void createExcel() throws IOException{
\t// 獲取桌面路徑
\tFileSystemView fsv = FileSystemView.getFileSystemView();
\tString desktop = fsv.getHomeDirectory().getPath();
\tString filePath = desktop + "/template.xls";
\t
\tFile file = new File(filePath);
\tOutputStream outputStream = new FileOutputStream(file);
\tHSSFWorkbook workbook = new HSSFWorkbook();
\tHSSFSheet sheet = workbook.createSheet("Sheet1");
\tHSSFRow row = sheet.createRow(0);
\trow.createCell(0).setCellValue("id");
\trow.createCell(1).setCellValue("訂單號");
\trow.createCell(2).setCellValue("下單時間");
\trow.createCell(3).setCellValue("個數");
\trow.createCell(4).setCellValue("單價");
\trow.createCell(5).setCellValue("訂單金額");
\trow.setHeightInPoints(30); // 設置行的高度
\t
\tHSSFRow row1 = sheet.createRow(1);
\trow1.createCell(0).setCellValue("1");
\trow1.createCell(1).setCellValue("NO00001");
\t
\t// 日期格式化
\tHSSFCellStyle cellStyle2 = workbook.createCellStyle();
\tHSSFCreationHelper creationHelper = workbook.getCreationHelper();

\tcellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
\tsheet.setColumnWidth(2, 20 * 256); // 設置列的寬度
\t
\tHSSFCell cell2 = row1.createCell(2);
\tcell2.setCellStyle(cellStyle2);
\tcell2.setCellValue(new Date());
\t
\trow1.createCell(3).setCellValue(2);
\t
\t
\t// 保留兩位小數
\tHSSFCellStyle cellStyle3 = workbook.createCellStyle();
\tcellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
\tHSSFCell cell4 = row1.createCell(4);
\tcell4.setCellStyle(cellStyle3);
\tcell4.setCellValue(29.5);
\t
\t
\t// 貨幣格式化
\tHSSFCellStyle cellStyle4 = workbook.createCellStyle();
\tHSSFFont font = workbook.createFont();
\tfont.setFontName("華文行楷");
\tfont.setFontHeightInPoints((short)15);
\tfont.setColor(HSSFColor.RED.index);
\tcellStyle4.setFont(font);
\t
\tHSSFCell cell5 = row1.createCell(5);
\tcell5.setCellFormula("D2*E2"); // 設置計算公式
\t
\t// 獲取計算公式的值
\tHSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
\tcell5 = e.evaluateInCell(cell5);
\tSystem.out.println(cell5.getNumericCellValue());
\t
\tworkbook.setActiveSheet(0);
\tworkbook.write(outputStream);
\toutputStream.close();
}/<code>

示例2:讀取Excel,解析數據

<code>public static void readExcel() throws IOException{
\tFileSystemView fsv = FileSystemView.getFileSystemView();
\tString desktop = fsv.getHomeDirectory().getPath();

\tString filePath = desktop + "/template.xls";
\t
\tFileInputStream fileInputStream = new FileInputStream(filePath);
\tBufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
\tPOIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
\tHSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
\tHSSFSheet sheet = workbook.getSheet("Sheet1");
\t
\tint lastRowIndex = sheet.getLastRowNum();
\tSystem.out.println(lastRowIndex);
\tfor (int i = 0; i <= lastRowIndex; i++) {
\t\tHSSFRow row = sheet.getRow(i);
\t\tif (row == null) { break; }
\t\t
\t\tshort lastCellNum = row.getLastCellNum();
\t\tfor (int j = 0; j < lastCellNum; j++) {
\t\t\tString cellValue = row.getCell(j).getStringCellValue();
\t\t\tSystem.out.println(cellValue);
\t\t}
\t}
\t
\t
\tbufferedInputStream.close();
}/<code>

四:Java Web 中導出和導入Excel

1、導出示例

<code>@SuppressWarnings("resource")
@RequestMapping("/export")
public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception {
\t
\tString[] tableHeaders = {"id", "姓名", "年齡"};
\t
\tHSSFWorkbook workbook = new HSSFWorkbook();
\tHSSFSheet sheet = workbook.createSheet("Sheet1");
\tHSSFCellStyle cellStyle = workbook.createCellStyle();
\tcellStyle.setAlignment(HorizontalAlignment.CENTER);
\tcellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
\t
\tFont font = workbook.createFont();
\tfont.setColor(HSSFColor.RED.index);
\tfont.setBold(true);
\tcellStyle.setFont(font);
\t
\t// 將第一行的三個單元格給合併

\tsheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
\tHSSFRow row = sheet.createRow(0);
\tHSSFCell beginCell = row.createCell(0);
\tbeginCell.setCellValue("通訊錄");\t
\tbeginCell.setCellStyle(cellStyle);
\t
\trow = sheet.createRow(1);
\t// 創建表頭
\tfor (int i = 0; i < tableHeaders.length; i++) {
\t\tHSSFCell cell = row.createCell(i);
\t\tcell.setCellValue(tableHeaders[i]);
\t\tcell.setCellStyle(cellStyle);
\t}
\t
\tList<user> users = new ArrayList<>();
\tusers.add(new User(1L, "張三", 20));
\tusers.add(new User(2L, "李四", 21));
\tusers.add(new User(3L, "王五", 22));
\t
\tfor (int i = 0; i < users.size(); i++) {
\t\trow = sheet.createRow(i + 2);
\t\t
\t\tUser user = users.get(i);
\t\trow.createCell(0).setCellValue(user.getId());
\t\trow.createCell(1).setCellValue(user.getName());
\t\trow.createCell(2).setCellValue(user.getAge());
\t}
\t
\tOutputStream outputStream = response.getOutputStream();
\tresponse.reset();
\tresponse.setContentType("application/vnd.ms-excel");
\tresponse.setHeader("Content-disposition", "attachment;filename=template.xls");
\tworkbook.write(outputStream);
\toutputStream.flush();
\toutputStream.close();
}/<user>/<code>

2、導入示例

1、使用SpringMVC上傳文件,需要用到commons-fileupload

<code><dependency>
\t<groupid>commons-fileupload/<groupid>
\t<artifactid>commons-fileupload/<artifactid>
\t<version>1.3/<version>
/<dependency>/<code>

2、需要在spring的配置文件中配置一下multipartResolver

<code><bean> \tclass="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
\t<property>
/<bean>/<code>

3、index.jsp

<code>  

/<code>

4、解析上傳的.xls文件

<code>@SuppressWarnings("resource")
@RequestMapping("/import")
public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
\tInputStream inputStream = file.getInputStream();
\tBufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
\tPOIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
\tHSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
\t//HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
\tHSSFSheet sheet = workbook.getSheetAt(0);
\t
\tint lastRowNum = sheet.getLastRowNum();
\tfor (int i = 2; i <= lastRowNum; i++) {
\t\tHSSFRow row = sheet.getRow(i);
\t\tint id = (int) row.getCell(0).getNumericCellValue();
\t\tString name = row.getCell(1).getStringCellValue();
\t\tint age = (int) row.getCell(2).getNumericCellValue();
\t\t
\t\tSystem.out.println(id + "-" + name + "-" + age);
\t}
}/<code>

導出效果:

Apache POI使用詳解(看完這篇基本上能應付工作中常用的excel)

導入效果:

Apache POI使用詳解(看完這篇基本上能應付工作中常用的excel)


分享到:


相關文章: