繁体   English   中英

如何使用 Java 将 CSV 文件加载到 Excel 工作表中

[英]How can I load CSV file into Excel sheet using Java

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

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

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

我会遵循这种方法:

  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文件后,您可以按照此问题创建.csv文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM