如何防止输出excel文件损坏?

hs1ihplo  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(490)

我正在用下面的代码创建一个报表,并使用quartz scheduler对其进行调度,但当它保存时,它已损坏。。

public class GenerateReport implements Job{

    XSSFWorkbook report = new XSSFWorkbook();
    MyData myData = new MyData();

    public XSSFWorkbook createReport() {
        Map<Integer, String> data = new HashMap<Integer, String>();
        myData.setData(1652, "Abcs");
        myData.setData(1682, "ksaos");
        myData.setData(1152, "oass");
        myData.setData(1962, "Aajas");

        data = myData.getData();

        XSSFSheet sheet = report.createSheet("Employee data");
        XSSFCellStyle headerStyle = report.createCellStyle();

        XSSFFont headerFont = report.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        XSSFCell cell = null;
        XSSFRow row;
        int rowNum = 0;
        int colNum = 0;

        row = sheet.createRow(rowNum++);
        row.createCell(colNum++).setCellValue("ID");
        row.createCell(colNum).setCellValue("Name");

        for(Map.Entry<Integer, String> entry: data.entrySet()) {
            colNum = 0;
            row = sheet.createRow(rowNum++);
            cell = row.createCell(colNum++);
            cell.setCellValue(entry.getKey());

            cell = row.createCell(colNum);
            cell.setCellValue(entry.getValue());
        }

        return report;
    }

    public void saveReport() {
        XSSFWorkbook finalWorkbook = new XSSFWorkbook();
        try {
            FileOutputStream fos = new FileOutputStream("C:\\Users\\ra185586\\Desktop\\written.xlsx");
            finalWorkbook.write(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.print("Report generated");
    }

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        createReport();
        saveReport();
        System.out.println(" and saved");

    }
}

你们能帮我解决这个问题吗?这样当报表保存时,它就不会损坏了。谢谢您!

pgx2nnw8

pgx2nnw81#

方法createreport()返回xssfworkbook。您需要将这个xssfworkbook转移到savereport。
-变化 execute 两行打开 saveReport(createReport()); -删除中的行
saveReport XSSFWorkbook finalWorkbook = new XSSFWorkbook(); -在中添加参数
saveReport saveReport(XSSFWorkbook finalWorkbook)

相关问题