1. 程式人生 > >java 生成excel 支援 xls、xlsx

java 生成excel 支援 xls、xlsx

java小工具專案

最近由於工作需要寫了個小工具專案,用來生產excel,其中參考了poi官網的demo,以及網路上的一些資料。:

  • 引入jar
<poi.version>3.17</poi.version>
 <!--poi相關-->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>${poi.version}</version
>
</dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId> <version>${poi.version}</version> </dependency> <!--poi相關-->
  • 核心程式碼
/**
     * 生成 xlsx格式的excel
     *
     * @param fileName   檔名稱  如 xxx.xls
     * @param filePath   檔案路徑  如 D:\export\
     * @param
fileSuffix 檔案字尾 * @param list 資料 * @throws IOException */
public static void exportExcelXlsx(String fileName, String filePath, String fileSuffix, List<Map<String, Object>> list, String showType) throws IOException { long start = System.currentTimeMillis(); // 宣告一個工作薄 XSSFWorkbook workBook = new XSSFWorkbook(); int s = 0; for (Map<String, Object> map : list) { String sheetName = map.get("sheetName").toString(); String[] sheetHead = (String[]) map.get("sheetHead"); List<String[]> dataList = (List<String[]>) map.get("sheetData"); String serialNumber = map.get("serialNumber").toString(); String serialNumberDesc = map.get("serialNumberDesc").toString(); String calcTimeIndex = map.get("calcTimeIndex").toString();//取第幾列的值來計算時間片段 -1 表示不計算 0 表示計算第一個 以此類推 // 生成一個表格 XSSFSheet sheet = workBook.createSheet(); workBook.setSheetName(s, sheetName); // 建立表格標題行 第一行 XSSFRow titleRow = sheet.createRow(0); //需要加入序號列 if (StringUtils.equals("1", serialNumber)) { titleRow.createCell(0).setCellValue(serialNumberDesc); for (int i = 1; i < sheetHead.length+1; i++) { titleRow.createCell(i).setCellValue(sheetHead[i - 1]); } //插入需匯出的資料 for (int i = 0; i < dataList.size(); i++) { XSSFRow row = sheet.createRow(i + 1); row.createCell(0).setCellValue((i + 1)); for (int j = 1; j < sheetHead.length + 1; j++) { //計算時間片 if (!StringUtils.equals("-1", calcTimeIndex)) { if (Integer.valueOf(calcTimeIndex) == (j - 1)) { row.createCell(j).setCellValue(getStepIntexTime(Integer.valueOf(dataList.get(i)[j - 1]))); } else { row.createCell(j).setCellValue(dataList.get(i)[j - 1]); } } else { row.createCell(j).setCellValue(dataList.get(i)[j - 1]); } } } } else { //不需要加入序號列 for (int i = 0; i < sheetHead.length; i++) { titleRow.createCell(i).setCellValue(sheetHead[i]); } //插入需匯出的資料 for (int i = 0; i < dataList.size(); i++) { XSSFRow row = sheet.createRow(i + 1); for (int j = 0; j < sheetHead.length; j++) { //計算時間片 if (!StringUtils.equals("-1", calcTimeIndex)) { if (Integer.valueOf(calcTimeIndex) == j) { row.createCell(j).setCellValue(getStepIntexTime(Integer.valueOf(dataList.get(i)[j]))); } else { row.createCell(j).setCellValue(dataList.get(i)[j]); } } else { row.createCell(j).setCellValue(dataList.get(i)[j]); } } } } s++; } //校驗檔案路徑是否存在 File checkPath = new File(filePath); if (!checkPath.exists()) { checkPath.mkdirs(); } if (!filePath.endsWith(File.separator)) { filePath = filePath + File.separator; } File file = new File(filePath + fileName + "." + fileSuffix); //檔案輸出流 FileOutputStream outStream = new FileOutputStream(file); workBook.write(outStream); outStream.flush(); outStream.close(); LogShowUtils.show(showType, log, "生成檔案耗時:" + (System.currentTimeMillis() - start)); LogShowUtils.show(showType, log, "匯出檔案成功!檔案匯出路徑:--" + filePath + fileName); }
 /**
     * 生成 xls格式的excel
     *
     * @param fileName   檔名稱  如 xxx.xls
     * @param filePath   檔案路徑  如 D:\export\
     * @param fileSuffix 檔案字尾
     * @param list       資料
     * @throws IOException
     */
    public static void exportExcelXls(String fileName, String filePath, String fileSuffix, List<Map<String, Object>> list, String showType) throws IOException {

        long start = System.currentTimeMillis();
        try (HSSFWorkbook wb = new HSSFWorkbook()) {

            int s = 0;
            for (Map<String, Object> map : list) {
                String sheetName = map.get("sheetName").toString();
                String[] sheetHead = (String[]) map.get("sheetHead");
                String serialNumber = map.get("serialNumber").toString();
                List<String[]> dataList = (List<String[]>) map.get("sheetData");

                String serialNumberDesc = map.get("serialNumberDesc").toString();
                String calcTimeIndex = map.get("calcTimeIndex").toString();//取第幾列的值來計算時間片段 -1 表示不計算  0 表示計算第一個 以此類推
                HSSFSheet sheet = wb.createSheet(sheetName);

                // Create a row and put some cells in it. Rows are 0 based.
                HSSFRow titleRow = sheet.createRow(0);
                //需要加入序號列
                if (StringUtils.equals("1", serialNumber)) {
                    titleRow.createCell(0).setCellValue(serialNumberDesc);
                    for (int i = 1; i < sheetHead.length+1; i++) {

                        titleRow.createCell(i).setCellValue(sheetHead[i - 1]);
                    }
                    //插入需匯出的資料
                    for (int i = 0; i < dataList.size(); i++) {
                        HSSFRow row = sheet.createRow(i + 1);
                        row.createCell(0).setCellValue((i + 1));
                        for (int j = 1; j < sheetHead.length + 1; j++) {
                            //計算時間片
                            if (!StringUtils.equals("-1", calcTimeIndex)) {
                                if (Integer.valueOf(calcTimeIndex) == (j - 1)) {
                                    row.createCell(j).setCellValue(getStepIntexTime(Integer.valueOf(dataList.get(i)[j - 1])));
                                } else {
                                    row.createCell(j).setCellValue(dataList.get(i)[j - 1]);
                                }
                            } else {
                                row.createCell(j).setCellValue(dataList.get(i)[j - 1]);
                            }
                        }
                    }
                } else {
                    //不需要加入序號列

                    for (int i = 0; i < sheetHead.length; i++) {
                        titleRow.createCell(i).setCellValue(sheetHead[i]);
                    }
                    //插入需匯出的資料
                    for (int i = 0; i < dataList.size(); i++) {
                        HSSFRow row = sheet.createRow(i + 1);
                        for (int j = 0; j < sheetHead.length; j++) {

                            //計算時間片
                            if (!StringUtils.equals("-1", calcTimeIndex)) {
                                if (Integer.valueOf(calcTimeIndex) == j) {
                                    row.createCell(j).setCellValue(getStepIntexTime(Integer.valueOf(dataList.get(i)[j])));
                                } else {
                                    row.createCell(j).setCellValue(dataList.get(i)[j]);
                                }
                            } else {
                                row.createCell(j).setCellValue(dataList.get(i)[j]);
                            }

                        }
                    }
                }

                s++;
            }

            //校驗檔案路徑是否存在
            File checkPath = new File(filePath);
            if (!checkPath.exists()) {
                checkPath.mkdirs();
            }
            if (!filePath.endsWith(File.separator)) {

                filePath = filePath + File.separator;
            }
            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream(filePath + fileName + "." + fileSuffix)) {
                wb.write(fileOut);
                fileOut.close();
            }

            LogShowUtils.show(showType, log, "生成檔案耗時:" + (System.currentTimeMillis() - start));
            LogShowUtils.show(showType, log, "匯出檔案成功!檔案匯出路徑:--" + filePath + fileName);
        }
    }