alibaba/easyexcel

在已有的文件写excel内容

Open

#3957 aperta il 28 ago 2024

Vedi su GitHub
 (0 commenti) (0 reazioni) (0 assegnatari)Java (7599 fork)batch import
help wanted

Metriche repository

Star
 (33.728 star)
Metriche merge PR
 (Nessuna PR mergiata in 30 g)

Descrizione

重复写同一个excel会出现内容覆盖,或者excel文件被破坏,现在目前的Excel是否支持在已有的excel追加数据

异常代码

   
        String filePath = "F:\\export.xlsx";
        File excelFile=new File(filePath) ;
        Integer flag=param.getFlag();

        //不是结束标识写入excel
            OutputStream outputStream = null;
            InputStream inputStream=null;
            if (flag == -1) {
                // 结束标志,关闭写入器
                if (writer!= null) {
                    writer.finish();
                    writer=null;
                }
            } else {
                if (!excelFile.exists()) {
                    log.info("文件不存在,创建新的 Excel 文件并写入数据");
                    //excelFile.createNewFile();
                    // 文件不存在,创建新的 Excel 文件并写入数据
                    writer = EasyExcel.write(excelFile).registerConverter(new TimestampConverter()).build();
                    WriteSheet sheet1 = EasyExcel.writerSheet("OldSheet"+sheetCount).build();
                    writer.write(dataList, sheet1);
                    sheetCount++;
                } else {
                    // 文件已存在,继续写入数据
                    log.info("文件已存在,继续写入数据");
                    System.out.println(excelFile.length());
                    try {
                        outputStream=new FileOutputStream(excelFile);
                        inputStream=new FileInputStream(excelFile);
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                    // 读取现有文件获取工作簿对象

                    writer = EasyExcel.write(filePath, null).registerConverter(new TimestampConverter()).build();
                    WriteSheet sheet2 = EasyExcel.writerSheet("newSheet"+sheetCount).build();

                    sheetCount++;
                    writer.write(dataList, sheet2);
                }

异常提示

大家尽量把问题一次性描述清楚,然后贴上全部异常,这样方便把问题一次性解决掉。 至少大家要符合一个原则就是,能让其他人复现出这个问题,如果无法复现,肯定无法解决。

问题描述

Guida contributor