简体   繁体   English

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

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

I have an Excel spreadsheet that has the first sheet designated for the raw data.我有一个 Excel 电子表格,其中包含为原始数据指定的第一张工作表。 There are 3 more sheets that are coded to transform and format the data from the raw sheet.还有 3 个工作表被编码来转换和格式化来自原始工作表的数据。 The fifth sheet has the final output.第五张纸有最终输出。 How can I use Java:我如何使用 Java:

  1. load the data from the CSV file into the first sheet of the excel file?将 CSV 文件中的数据加载到 Excel 文件的第一张表中?
  2. save the data from the 5th sheet into the new CSV file.将第 5 个工作表中的数据保存到新的 CSV 文件中。

Also, if the original CSV has thousands of rows, I assume the multi-sheet transformations would take some time before the 5th sheet gets all the final data - is there a way to know?另外,如果原始 CSV 有数千行,我认为在第 5 个工作表获得所有最终数据之前,多工作表转换需要一些时间 - 有没有办法知道?

I would follow this approach:我会遵循这种方法:

  1. Load the specific .csv file and prepare to read it with Java加载特定的.csv文件并准备用 Java 读取它
  2. Load the .xlsx file and change it according to your requirements and the data that you get from the .csv file.加载.xlsx文件并根据您的要求和从.csv文件中获取的数据进行更改。 A small example of how an excel file is changed with Apache POI can be seen below:下面是如何使用 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. After saving the .xlsx file, you can create the .csv file by following this question .保存.xlsx文件后,您可以按照此问题创建.csv文件。

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

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