Java匯入匯出Excel表格(xls版本、xlsx版本)
阿新 • • 發佈:2018-11-27
自己整合成的一個專門匯入匯出工具類
一、pom檔案導包:
<!-- 匯入匯出Excel表格 --> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.11-beta2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8</version> </dependency>
二、匯入匯出工具類:
package com.zzdz.tools; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.xssf.usermodel.XSSFCell; 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.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; /** * * Title: OperationExcelUtil * Description: 匯入匯出Excel表格 * Version:1.0.0 * @author liuxin * @date 2018年10月15日 * @param <T> */ @SuppressWarnings({ "unchecked", "rawtypes", "resource" }) public class OperationExcelUtil<T> { // 2007 版本以上 最大支援1048576行 public final static String EXCEl_FILE_2007 = "2007"; // 2003 版本 最大支援65536 行 public final static String EXCEL_FILE_2003 = "2003"; /** * <p> * 匯出無頭部標題行Excel <br> * 時間格式預設:yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格標題 * @param dataset 資料集合 * @param out 輸出流 * @param version 2003 或者 2007,不傳時預設生成2003版本 */ public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) { if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) { exportExcel2003(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss"); } else { exportExcel2007(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss"); } } /** * <p> * 匯出帶有頭部標題行的Excel <br> * 時間格式預設:yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格標題 * @param headers 頭部標題集合 * @param dataset 資料集合 * @param out 輸出流 * @param version 2003 或者 2007,不傳時預設生成2003版本 */ public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String version) { if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) { exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss"); } else { exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss"); } } /** * <p> * 通用Excel匯出方法,利用反射機制遍歷物件的所有欄位,將資料寫入Excel檔案中 <br> * 此版本生成2007以上版本的檔案 (檔案字尾:xlsx) * </p> * * @param title 表格標題名 * @param headers 表格頭部標題集合 * @param dataset 需要顯示的資料集合,集合中一定要放置符合JavaBean風格的類的物件。此方法支援的JavaBean屬性的資料型別有基本資料型別及String,Date * @param out 與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中 * @param pattern 如果有時間資料,設定輸出格式。預設為"yyyy-MM-dd hh:mm:ss" */ /** * 上述註解是jse提供的註解。作用是遮蔽一些無關緊要的警告。使開發者能看到一些他們真正關心的警告。從而提高開發者的效率 * 使用的話 是這樣suppressWarnings 禁止顯示警告 */ public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) { // 宣告一個工作薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個表格 XSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth(20); // 生成一個樣式 XSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray)); style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 生成一個字型 XSSFFont font = workbook.createFont(); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setColor(new XSSFColor(java.awt.Color.BLACK)); font.setFontHeightInPoints((short) 11); // 把字型應用到當前的樣式 style.setFont(font); // 生成並設定另一個樣式 XSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE)); style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(XSSFCellStyle.BORDER_THIN); style2.setBorderLeft(XSSFCellStyle.BORDER_THIN); style2.setBorderRight(XSSFCellStyle.BORDER_THIN); style2.setBorderTop(XSSFCellStyle.BORDER_THIN); style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 生成另一個字型 XSSFFont font2 = workbook.createFont(); font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL); // 把字型應用到當前的樣式 style2.setFont(font2); // 產生表格標題行 XSSFRow row = sheet.createRow(0); XSSFCell cellHeader; for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(style); cellHeader.setCellValue(new XSSFRichTextString(headers[i])); } // 遍歷集合資料,產生資料行 Iterator<T> it = dataset.iterator(); int index = 0; T t; Field[] fields; Field field; XSSFRichTextString richString; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher; String fieldName; String getMethodName; XSSFCell cell; Class tCls; Method getMethod; Object value; String textValue; SimpleDateFormat sdf = new SimpleDateFormat(pattern); while (it.hasNext()) { index++; row = sheet.createRow(index); t = (T) it.next(); // 利用反射,根據JavaBean屬性的先後順序,動態呼叫getXxx()方法得到屬性值 fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { cell = row.createCell(i); cell.setCellStyle(style2); field = fields[i]; fieldName = field.getName(); getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { tCls = t.getClass(); getMethod = tCls.getMethod(getMethodName, new Class[] {}); value = getMethod.invoke(t, new Object[] {}); // 判斷值的型別後進行強制型別轉換 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它資料型別都當作字串簡單處理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new XSSFRichTextString(textValue); cell.setCellValue(richString); } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { // 清理資源 } } } try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } /** * <p> * 通用Excel匯出方法,利用反射機制遍歷物件的所有欄位,將資料寫入Excel檔案中 <br> * 此方法生成2003版本的excel,檔名字尾:xls <br> * </p> * * @param title 表格標題名 * @param headers 表格頭部標題集合 * @param dataset 需要顯示的資料集合,集合中一定要放置符合JavaBean風格的類的物件。此方法支援的JavaBean屬性的資料型別有基本資料型別及String,Date * @param out 與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中 * @param pattern 如果有時間資料,設定輸出格式。預設為"yyyy-MM-dd hh:mm:ss" */ public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) { // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth(20); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一個字型 HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setColor(HSSFColor.WHITE.index); font.setFontHeightInPoints((short) 11); // 把字型應用到當前的樣式 style.setFont(font); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.WHITE.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一個字型 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字型應用到當前的樣式 style2.setFont(font2); // 產生表格標題行 HSSFRow row = sheet.createRow(0); HSSFCell cellHeader; for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(style); cellHeader.setCellValue(new HSSFRichTextString(headers[i])); } // 遍歷集合資料,產生資料行 Iterator<T> it = dataset.iterator(); int index = 0; T t; Field[] fields; Field field; HSSFRichTextString richString; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher; String fieldName; String getMethodName; HSSFCell cell; Class tCls; Method getMethod; Object value; String textValue; SimpleDateFormat sdf = new SimpleDateFormat(pattern); while (it.hasNext()) { index++; row = sheet.createRow(index); t = (T) it.next(); // 利用反射,根據JavaBean屬性的先後順序,動態呼叫getXxx()方法得到屬性值 fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { cell = row.createCell(i); cell.setCellStyle(style2); field = fields[i]; fieldName = field.getName(); getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { tCls = t.getClass(); getMethod = tCls.getMethod(getMethodName, new Class[] {}); value = getMethod.invoke(t, new Object[] {}); // 判斷值的型別後進行強制型別轉換 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它資料型別都當作字串簡單處理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new HSSFRichTextString(textValue); cell.setCellValue(richString); } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { // 清理資源 } } } try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } /*******************************************************************************************************************/ /** * <p> * 匯入Excel表格E <br> * </p> * * @param templetFile 檔案 * @param startrow 開始行號 * @param startcol 開始列號 * @param sheetnum * @return */ public static List<Map<String,String>> readExcel(MultipartFile templetFile, int startrow, int startcol, int sheetnum){ List<Map<String,String>> varList = new ArrayList<Map<String,String>>(); if(templetFile!=null&&templetFile.getSize()>0){ String ofn=templetFile.getOriginalFilename();// 檔名 String extName = ""; // 副檔名格式: if (ofn.lastIndexOf(".") >= 0){ extName = ofn.substring(ofn.lastIndexOf(".")); } if(".xls".equals(extName.toLowerCase())){ varList=readExcelByXls(templetFile,startrow,startcol,sheetnum); }else if(".xlsx".equals(extName.toLowerCase())){ varList=readExcelByXlsx(templetFile,startrow,startcol,sheetnum); } } return varList; } /** * 操作Excel2003以前(包括2003)的版本,副檔名是.xls * @param templetFile 檔案 * @param startrow 開始行號 * @param startcol 開始列號 * @param sheetnum sheet * @return list */ public static List<Map<String, String>> readExcelByXls(MultipartFile templetFile, int startrow, int startcol, int sheetnum) { List<Map<String, String>> varList = new ArrayList<Map<String, String>>(); try { HSSFWorkbook wb = new HSSFWorkbook(templetFile.getInputStream()); HSSFSheet sheet = wb.getSheetAt(sheetnum); // sheet 從0開始 int rowNum = sheet.getLastRowNum() + 1; // 取得最後一行的行號 for (int i = startrow; i < rowNum; i++) { // 行迴圈開始 Map<String, String> varpd = new HashMap<String, String>(); HSSFRow row = sheet.getRow(i); // 行 int cellNum = row.getLastCellNum(); // 每行的最後一個單元格位置 for (int j = startcol; j < cellNum; j++) { // 列迴圈開始 HSSFCell cell = row.getCell(Integer.parseInt(j + "")); String cellValue = null; if (null != cell) { switch (cell.getCellType()) { // 判斷excel單元格內容的格式,並對其進行轉換,以便插入資料庫 case 0: if (HSSFDateUtil.isCellDateFormatted(cell)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString(); } else { cell.setCellType(1); cellValue = cell.getStringCellValue(); } break; case 1: cellValue = cell.getStringCellValue(); break; case 2: // cell.setCellType(1); // cellValue = cell.getStringCellValue(); // cellValue = cell.getNumericCellValue() + ""; cellValue = String.valueOf(cell.getDateCellValue()); break; case 3: cellValue = ""; break; case 4: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case 5: cellValue = String.valueOf(cell.getErrorCellValue()); break; } } else { cellValue = ""; } varpd.put("var" + j, cellValue); } varList.add(varpd); } } catch (Exception e) { System.out.println(e); } return varList; } /** * 是操作Excel2007的版本,副檔名是.xlsx * @param templetFile 檔案 * @param startrow 開始行號 * @param startcol 開始列號 * @param sheetnum sheet * @return list */ public static List<Map<String, String>> readExcelByXlsx(MultipartFile templetFile, int startrow, int startcol, int sheetnum) { List<Map<String, String>> varList = new ArrayList<Map<String, String>>(); try { XSSFWorkbook wb = new XSSFWorkbook(templetFile.getInputStream()); XSSFSheet sheet = wb.getSheetAt(sheetnum); // sheet 從0開始 int rowNum = sheet.getLastRowNum() + 1; // 取得最後一行的行號 for (int i = startrow; i < rowNum; i++) { // 行迴圈開始 Map<String, String> varpd = new HashMap<String, String>(); XSSFRow row = sheet.getRow(i); // 行 int cellNum = row.getLastCellNum(); // 每行的最後一個單元格位置 for (int j = startcol; j < cellNum; j++) { // 列迴圈開始 XSSFCell cell = row.getCell(Integer.parseInt(j + "")); String cellValue = null; if (null != cell) { switch (cell.getCellType()) { // 判斷excel單元格內容的格式,並對其進行轉換,以便插入資料庫 case 0: if (HSSFDateUtil.isCellDateFormatted(cell)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString(); } else { cell.setCellType(1); cellValue = cell.getStringCellValue(); } break; case 1: cellValue = cell.getStringCellValue(); break; case 2: cellValue = cell.getStringCellValue(); // cellValue = cell.getNumericCellValue() + ""; // cellValue = // String.valueOf(cell.getDateCellValue()); break; case 3: cellValue = ""; break; case 4: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case 5: cellValue = String.valueOf(cell.getErrorCellValue()); break; } } else { cellValue = ""; } varpd.put("var" + j, cellValue); } varList.add(varpd); } } catch (Exception e) { System.out.println(e); } return varList; } }