小而美的工具类(1)-EXCEL转CSV

POM
<dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-csv</artifactId>
      <version>1.8</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>YOUR_POI_VERSION</version>
</dependency>

工具类

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileWriter;

public class ExcelToCSV {
    public static void change(String excelFilePath, String csvFilePath) throws Exception {
        Workbook workbook = WorkbookFactory.create(new File(excelFilePath));
        Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet

        try (
                FileWriter fileWriter = new FileWriter(csvFilePath);
                CSVPrinter csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT)
        ) {
            for (Row row : sheet) {
                String[] columns = row.iterator().hasNext() ? new String[row.getLastCellNum()] : new String[0];
                int i = 0;
                for (Cell cell : row) {
                    columns[i++] = getCellValueAsString(cell);
                }
                csvPrinter.printRecord(columns);
            }
        }
    }

    private static String getCellValueAsString(Cell cell) {
        switch (cell.getCellTypeEnum()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}

 

posted @ 2024-03-22 15:56  左手程序,右手诗  阅读(15)  评论(0编辑  收藏  举报