1. 程式人生 > 實用技巧 >[20-10-31][Taste 2]Java poi

[20-10-31][Taste 2]Java poi

package com.kiyuumirai.project;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author MirAi
 * @description Excel流
 * @date 2020/10/31 18:37
 */
public final class ExcelIo {

    /**
     * 根據源路徑名讀取excel檔案
     *
     * @param fromPath 源路徑名
     * 
@return workbook物件 */ public static XSSFWorkbook getInWorkBookByPath(String fromPath) { try (FileInputStream in = new FileInputStream(fromPath)) { // 將讀取出的檔案流封裝為XSSFWorkbook物件 return new XSSFWorkbook(in); } catch (Exception e) { e.printStackTrace(); }
return null; } /** * 根據workbook物件向目標路徑寫入excel內容 * * @param workbook workbook物件 * @param toPath 目標路徑 */ public static void writeWorkBook(XSSFWorkbook workbook, String toPath) { try (FileOutputStream out = new FileOutputStream(toPath)) { // 將XSSFWorkbook物件中的內容寫入檔案
workbook.write(out); } catch (Exception e) { e.printStackTrace(); } } }

package com.kiyuumirai.project;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.xssf.usermodel.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author MirAi
 * @description Excel工具類
 * @date 2020/10/31 18:26
 */
public final class ExcelUtil {

    /** 資料快取 */
    private static List<List<Object>> data = new ArrayList<>();
    /** excel副檔名 */
    private static final String SUFFIX_NAME = "xlsx";

    static {

        // 第一列內容
        List<Object> titles = new ArrayList<>();

        titles.add("姓名");
        titles.add("任務");
        titles.add("遇到的問題");
        titles.add("是否解決");
        titles.add("解決方案");
        titles.add("備註");
        titles.add("日期");
        data.add(titles);
    }

    /**
     * 將內容複製到同一個excel
     *
     * @param srcDirPath 原始檔目錄
     * @param targetSheetName 目標excel工作表名
     */
    public static void copy(String srcDirPath, String targetSheetName) {

        readDir(srcDirPath);

        final String targetDir = srcDirPath + "/result";
        final String targetFileName = targetDir + "/result.xlsx";

        // 在源目錄下建立目標資料夾
        File dir = new File(targetDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 在目標資料夾下建立目標excel檔案
        File file = new File(targetFileName);
        if (!file.exists()) {
            ExcelIo.writeWorkBook(new XSSFWorkbook(), targetFileName);
        }

        // 讀取目標excel檔案
        XSSFWorkbook workbook = ExcelIo.getInWorkBookByPath(targetFileName);

        if (workbook != null) {
            // 在目標excel檔案下建立指定的新工作表(不能和已經存在的工作表重名)
            XSSFWorkbook wb = createExcel(targetSheetName, workbook);
            // 將彙總的資料寫入檔案中
            ExcelIo.writeWorkBook(wb, targetFileName);
        }
    }

    /**
     * 遍歷讀取目錄中excel檔案
     *
     * @param srcDirPath 源目錄
     */
    private static void readDir(String srcDirPath) {

        Path path = Paths.get(srcDirPath);

        try {

            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                    String fileName = file.getFileName().toString();
                    String suffix = fileName.split("\\.")[1];

                    try {

                        // 遍歷目錄下的所有xlsx格式檔案,分別讀取資料並存入資料快取中
                        if (SUFFIX_NAME.equals(suffix)) {

                            XSSFWorkbook workbook = ExcelIo.getInWorkBookByPath(path + "\\" + fileName);
                            if (workbook != null) {
                                readExcel(workbook);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return super.visitFile(file, attrs);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 讀取工作表中資料
     *
     * @param workbook excel檔案
     */
    private static void readExcel(XSSFWorkbook workbook) {

        // 獲得excel檔案中的第一個工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 獲取工作表的總行數
        int rows = sheet.getPhysicalNumberOfRows();
        // 遍歷所有行
        for (int i = 1; i < rows; i++) {
            // 獲取對應行
            XSSFRow row = sheet.getRow(i);
            // 獲取對應行的列數
            int cols = row.getLastCellNum();
            // 儲存對應行資料的集合
            List<Object> tempList = new ArrayList<>();
            // 遍歷行內所有列
            for (int j = 0; j < cols; j++) {
                // 處理非空單元格
                if (row.getCell(j) != null) {
                    // 時間格式的單元格單獨處理
                    if (row.getCell(j).getCellType() == Cell.CELL_TYPE_NUMERIC) {
                        tempList.add(row.getCell(j).getDateCellValue());
                    } else {
                        tempList.add(row.getCell(j).getStringCellValue());
                    }
                } else {
                    // 空資料填充null
                    tempList.add(null);
                }
            }
            // 將各列資料加入資料快取
            data.add(tempList);
        }
    }

    /**
     * 根據資料和原始檔建立excel工作表
     *
     * @param workbook 原始檔
     * @return 填充資料後的excel檔案
     */
    private static XSSFWorkbook createExcel(String sheetName, XSSFWorkbook workbook) {

        // 根據指定名稱建立工作表
        XSSFSheet sheet = workbook.createSheet(sheetName);

        // 獲取資料快取的條數為行數
        int rows = data.size();
        // 獲取資料快取中每條資料內的資料條數作為列
        int cols = data.get(0).size();
        // 遍歷所有行
        for (int i = 0; i < rows; i++) {
            // 建立行
            XSSFRow row = sheet.createRow(i);
            // 遍歷所有列
            for (int j = 0; j < cols; j++) {
                // 建立單元格
                XSSFCell cell = row.createCell(j);
                // 將資料快取中的資料作為單元格資料
                Object cellData= data.get(i).get(j);
                // 判斷非空資料
                if (cellData != null) {
                    // 判斷資料是否為日期型別
                    if (cellData instanceof Date) {
                        // 建立單元格格式
                        XSSFCellStyle cellStyle = workbook.createCellStyle();
                        CreationHelper creationHelper = workbook.getCreationHelper();
                        // 將單元格格式設定為日期風格
                        cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy/MM/dd"));
                        // 儲存日期格式的資料
                        cell.setCellValue((Date) cellData);
                        cell.setCellStyle(cellStyle);
                    } else {
                        // 儲存普通文字資料
                        cell.setCellValue(cellData.toString());
                    }
                } else {
                    // 空資料填充空字串
                    cell.setCellValue("");
                }
            }
        }

        return workbook;
    }
}

package com.kiyuumirai.project;
/** 
 * @author MirAi
 * @description 主方法
 * @date 2020/10/31 18:52
 */
public class Main {

    public static void main(String[] args) {

        ExcelUtil.copy("D:\\Desktop\\1", "2020-10-31");
    }
}