Java利用POI讀寫Excel檔案工具類
阿新 • • 發佈:2021-01-04
本文例項為大家分享了Java讀寫Excel檔案工具類的具體程式碼,供大家參考,具體內容如下
package com.test.app.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.CollectionUtils; /** * @Description: Excel讀寫工具類 * @Author: hunger.zhu * @CreateDate: 2019/4/10 13:21 */ public class ExcelUtils { private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class); /** * 讀取Excel內容 * @param file 需要被讀的檔案物件 * @param startRow 從哪一行開始讀 (rowIndex從0開始的) * @param isExcel2003 是否是excel2003還是更高的版本 * @param sheetIndex 讀取哪一個sheet (sheetIndex也是從0開始) * @return List<List<String>> * @throws Exception */ public static List<List<String>> readExcel(File file,int startRow,boolean isExcel2003,int sheetIndex) throws Exception { List<List<String>> dataLst; InputStream is = null; try { /** 建立讀取檔案的輸入流 */ is = new FileInputStream(file); /** 根據版本選擇建立Workbook的方式 */ Workbook wb; if (isExcel2003) { wb = new HSSFWorkbook(is); } else { wb = new XSSFWorkbook(is); } /** 呼叫本類的讀取方法讀取excel資料 */ dataLst = read(wb,startRow,sheetIndex); } catch (Exception ex) { logger.error("讀取excel檔案異常!",ex); ex.printStackTrace(); throw ex; } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** 返回最後讀取的結果 */ return dataLst; } private static List<List<String>> read(Workbook wb,int sheetIndex) { /** 總列數 */ int totalCells = 0; /** 建立集合儲存讀取的資料 */ List<List<String>> dataLst = new ArrayList<List<String>>(); /** 得到第一個shell */ Sheet sheet = wb.getSheetAt(sheetIndex); /** 得到Excel的行數 */ int totalRows = sheet.getPhysicalNumberOfRows(); /** 得到Excel的列數 */ if (totalRows >= 1 && sheet.getRow(0) != null) { totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } /** 迴圈Excel的行 */ for (int r = startRow; ; r++) { Row row = sheet.getRow(r); if (row == null) { break; } List<String> rowLst = new ArrayList<String>(); /** 迴圈Excel的列 */ for (int c = 0; c < totalCells; c++) { Cell cell = row.getCell(c); String cellValue = ""; if (null != cell) { // 以下是判斷資料的型別 switch (cell.getCellTypeEnum()) { case NUMERIC: // 數字 // 判斷是不是日期格式 if (HSSFDateUtil.isCellDateFormatted(cell)) { cellValue = cell.getDateCellValue() + ""; }else { cellValue = cell.getNumericCellValue() + ""; } break; case STRING: // 字串 cellValue = cell.getStringCellValue(); break; case BOOLEAN: // Boolean cellValue = cell.getBooleanCellValue() + ""; break; case FORMULA: // 公式 cellValue = cell.getCellFormula() + ""; break; case BLANK: // 空值 cellValue = ""; break; case ERROR: // 故障 cellValue = "非法字元"; break; default: cellValue = "未知型別"; break; } } rowLst.add(cellValue); } /** 儲存第r行的第c列 */ boolean isEmptyRow = true; if (rowLst != null) { for (String s : rowLst) { if (s != null && !s.isEmpty()) { isEmptyRow = false; } } } if (!isEmptyRow) { dataLst.add(rowLst); } } return dataLst; } /** * 讀取Excel內容 * @param filePath 被讀取檔案的絕對路徑 * @param startRow * @param isExcel2003 * @param sheetIndex * @return List<List<String>> * @throws Exception */ public static List<List<String>> readExcel(String filePath,int sheetIndex) throws Exception { return readExcel(new File(filePath),isExcel2003,sheetIndex); } /** * 將資料寫入Excel工作簿 * @param header 表格的標題 * @param dataList 所需寫入的資料 List<List<String>> * @param isExcel2003 是否是excel2003還是更高的版本 * @param sheetName 生成的excel中sheet的名字 * @return Workbook 之後直接寫出即可,如workbook.write(new FileOutputStream("E://test/20190410_test.xlsx")); */ public static Workbook getWorkbookFromList(List<String> header,List<List<String>> dataList,String sheetName) { Workbook wb; // 建立Workbook物件(excel的文件物件) if (isExcel2003) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } // 建立新的sheet物件(excel的表單) Sheet sheet = wb.createSheet(sheetName); // 在sheet裡建立第一行,引數為行索引(excel的行),可以是0~65535之間的任何一個 int rowNum = 0; Row row0 = sheet.createRow(rowNum); if (!CollectionUtils.isEmpty(header)) { // 設定表頭 for (int i = 0; i < header.size(); i++) { Cell cell = row0.createCell(i); // 設定單元格樣式 cell.setCellStyle(POIUtils.getCellStyle(wb,"Calibri",(short) 12)); // 設定列寬 sheet.setColumnWidth(i,256 * 20); cell.setCellValue(header.get(i)); } rowNum++; } if (!CollectionUtils.isEmpty(dataList)) { // 填充資料 for (List<String> cellList : dataList) { Row row = sheet.createRow(rowNum); for (int i = 0; i < cellList.size(); i++) { Cell cell = row.createCell(i); cell.setCellStyle(POIUtils.getCellStyle(wb,(short) 12)); if (CollectionUtils.isEmpty(header)) { sheet.setColumnWidth(i,256 * 20); } cell.setCellValue(cellList.get(i)); } rowNum++; } } return wb; } /** * 將資料寫入Excel工作簿 * @param header 表格的標題 * @param dataList 所需寫入的資料 List<Object> * @param isExcel2003 是否是excel2003還是更高的版本 * @param sheetName 生成的excel中sheet的名字 * @return Workbook物件,之後直接寫出即可,如workbook.write(new FileOutputStream("E://test/20190410_test.xlsx")); * @throws Exception */ public static Workbook getWorkbookFromObj(List<String> header,List<?> dataList,String sheetName) throws Exception { Workbook wb; // 建立Workbook物件(excel的文件物件) if (isExcel2003) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } // 建立新的sheet物件(excel的表單) Sheet sheet = wb.createSheet(sheetName); // 在sheet裡建立第一行,引數為行索引(excel的行),可以是0~65535之間的任何一個 int rowNum = 0; Row row0 = sheet.createRow(rowNum); if (!CollectionUtils.isEmpty(header)) { // 設定表頭 for (int i = 0; i < header.size(); i++) { Cell cell = row0.createCell(i); // 設定單元格樣式 cell.setCellStyle(POIUtils.getCellStyle(wb,(short) 12)); sheet.setColumnWidth(i,256 * 20); cell.setCellValue(header.get(i)); } rowNum++; } if (!CollectionUtils.isEmpty(dataList)) { // 填充資料 Class<? extends Object> objClass = dataList.get(0).getClass(); Field[] fields = objClass.getDeclaredFields(); for (int i = 0; i < dataList.size(); i++) { // 建立row物件 Row row = sheet.createRow(rowNum); // 遍歷獲取每一個欄位的值 for (int j = 0; j < fields.length; j++) { String fieldVal = ""; Method[] methods = objClass.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equalsIgnoreCase("get" + fields[j].getName())) { String property = (String) method.invoke(dataList.get(i),null); fieldVal = property == null ? "" : property; break; } } Cell cell = row.createCell(j); cell.setCellStyle(POIUtils.getCellStyle(wb,(short) 12)); if (CollectionUtils.isEmpty(header)) { sheet.setColumnWidth(j,256 * 20); } cell.setCellValue(fieldVal); } rowNum++; } } return wb; } public static boolean validateExcel(String filePath) { /** 檢查檔名是否為空或者是否是Excel格式的檔案 */ if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) { // "檔名不是excel格式"; return false; } /** 檢查檔案是否存在 */ File file = new File(filePath); if (file == null || !file.exists()) { // "檔案不存在"; return false; } return true; } public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } }
以下為POIUtils.java:
package com.test.app.utils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.awt.*; import java.awt.Color; /** * @Description: Excel的單元格樣式 * @Author: hunger.zhu * @CreateDate: 2019/4/10 13:05 */ public class POIUtils { /** * 設定單元格的邊框(細)且為黑色,字型水平垂直居中,自動換行 * @param workbook * @param fontName * @param fontSize * @return */ public static CellStyle getCellStyle(Workbook workbook,String fontName,short fontSize){ CellStyle style = workbook.createCellStyle(); Font font = workbook.createFont(); // 設定上下左右四個邊框寬度 style.setBorderTop(BorderStyle.THIN); style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); // 設定上下左右四個邊框顏色 style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 水平居中,垂直居中,自動換行 style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); style.setWrapText(false); // 設定字型樣式及大小 font.setFontName(fontName); font.setFontHeightInPoints(fontSize); style.setFont(font); return style; } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。