gpt4 book ai didi

java - 如何防止输出 Excel 文件损坏?

转载 作者:行者123 更新时间:2023-12-01 18:27:42 28 4
gpt4 key购买 nike

我正在从以下代码创建一个报告并使用quartz调度程序调度它,但是当它被保存时,它被损坏了..

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");

}
}

你们能帮我解决一下吗,这样保存报告时就不会损坏。谢谢!

最佳答案

createReport() 方法返回 XSSFWorkbook。并且您需要将此XSSFWorkbook传输到saveReport。

-在 saveReport(createReport());

上更改 execute 两行

-删除 saveReport 中的行 XSSFWorkbook FinalWorkbook = new XSSFWorkbook();

-在 saveReport 中添加参数 saveReport(XSSFWorkbook FinalWorkbook)

关于java - 如何防止输出 Excel 文件损坏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206042/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com