【问题标题】:How can I load CSV file into Excel sheet using Java如何使用 Java 将 CSV 文件加载到 Excel 工作表中
【发布时间】:2021-07-13 04:15:22
【问题描述】:

我有一个 Excel 电子表格,其中第一张表指定用于原始数据。还有 3 个工作表被编码以转换和格式化原始工作表中的数据。第五张纸具有最终输出。 如何使用 Java:

  1. 将 CSV 文件中的数据加载到 excel 文件的第一张表中?
  2. 将第 5 页的数据保存到新的 CSV 文件中。

另外,如果原始 CSV 有数千行,我认为多表转换需要一些时间才能使第 5 张表获得所有最终数据 - 有没有办法知道?

【问题讨论】:

  • 你能用 VBA 代替吗? ;)

标签: java excel csv


【解决方案1】:

我会采用这种方法:

  1. 加载特定的.csv文件并准备用Java读取它
  2. 加载.xlsx 文件并根据您的要求和从.csv 文件中获得的数据进行更改。下面是一个关于如何使用 Apache POI 更改 excel 文件的小示例:
try
{
    HashMap<Integer, ArrayList<String>> fileData; // This for example keeps the data from the csv in this form ( 0 -> [ "Column1", "Column2" ]...)

    // Working with the excel file now
    FileInputStream file = new FileInputStream("Data.xlsx");

    XSSFWorkbook workbook = new XSSFWorkbook(file); // getting the Workbook
    XSSFSheet sheet = workbook.getSheetAt(0);
    Cell cell = null;

    AtomicInteger row = new AtomicInteger(0);
    fileData.forEach((key, csvRow) ->
    {
        //Update the value of the cell
        //Retrieve the row and check for null
        HSSFRow sheetRow = sheet.getRow(row);
        if(sheetRow == null)
        {
            sheetRow = sheet.createRow(row);
        }

        for (int i = 0; i < csvRow.size(); i++)
        {
            //Update the value of cell
            cell = sheetRow.getCell(i);
            if(cell == null){
                cell = sheetRow.createCell(i);
            }
            cell.setCellValue(csvRow.get(i));
        }

    });

    file.close();

    FileOutputStream outFile =new FileOutputStream(new File("Data.xlsx"));
    workbook.write(outFile);
    outFile.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
  1. 保存.xlsx文件后,您可以按照question创建.csv文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多