在Java中使用Apache POI导入Excel文件并保留内容的换行符

发布时间 2023-07-03 15:24:59作者: 迷糊桃
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

public class ReadExcelWithNewlines {
    public static void main(String[] args) {
        String filePath = "path/to/your/excel/file.xlsx";

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);

            // 遍历每一行
            for (Row row : sheet) {
                // 遍历每个单元格
                for (Cell cell : row) {
                    CellType cellType = cell.getCellType();
                    if (cellType == CellType.STRING) {
                        String cellValue = cell.getStringCellValue();
                        System.out.println("Cell Value: " + cellValue);
                    } else if (cellType == CellType.FORMULA) {
                        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                        CellValue cellValue = evaluator.evaluate(cell);
                        String formattedCellValue = formatFormulaCellValue(cellValue);
                        System.out.println("Cell Value: " + formattedCellValue);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String formatFormulaCellValue(CellValue cellValue) {
        switch (cellValue.getCellType()) {
            case STRING:
                return cellValue.getStringValue();
            case BOOLEAN:
                return String.valueOf(cellValue.getBooleanValue());
            case NUMERIC:
                return String.valueOf(cellValue.getNumberValue());
            default:
                return "";
        }
    }
}

注意在上面的代码中,我们使用了Apache POI库的XSSFWorkbook类和其他相关类来加载和读取Excel文件。该代码遍历了Excel表格中的每一行和每个单元格,并根据单元格类型获取相应的单元格值。

如果单元格内容是函数公式,我们使用FormulaEvaluator类计算其值。

请确保在运行上述代码之前将filePath变量设置为您实际的Excel文件路径。