gpt4 book ai didi

Java Spring - 编写 Excel 文件并转换为 PDF

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:44 34 4
gpt4 key购买 nike

希望有人能帮我解决这个问题。我目前正在一个 Java Spring 项目中工作(我对 Java 没有经验),我们需要一项服务来使用一些数据更新 Excel 模板并将其转换为 PDF。在下面的代码中,我使用 JFileChooser 来选择要编辑的 Template_RH 文件。编写完成后,会生成一个新的“Template_RH_updated”。

public class GenerateExcel {

public static void fillTable(List<ReportTable> table, Employee employee, String headerMonth) {

JFileChooser fileChooser = new JFileChooser();
int click = fileChooser.showOpenDialog(null);
if(click == JFileChooser.APPROVE_OPTION) {

try {
Workbook workbook = new HSSFWorkbook( new FileInputStream(fileChooser.getSelectedFile()));
Sheet sheet = workbook.getSheetAt(0);

//HERE WE HAVE THE CODE TO WRITE IN THE EXCEL FILE
// AFTER WE ARE DONE WRITING IN THE FILE

FileOutputStream outFile =new FileOutputStream(new File("Template_RH_updated.xls"));
workbook.write(outFile);
outFile.close();


} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

第一个问题是我想摆脱 JFileChooser。我想从项目本身获取文件。我将模板文件添加到项目中:

/myProject/src/main/resources/file/Template_RH.xls

但使用:

FileInputStream file = new FileInputStream("/myProject/src/main/resources/file/Template_RH.xls");

不工作。这样做的正确方法是什么?另外,是否可以让客户端在通过浏览器调用服务时下载这个文件?

我的最后一个问题是,是否有人知道如何将此 Excel 文件转换为 PDF。如果有任何图书馆不能帮助我完成这项任务。

谢谢!

最佳答案

尝试:

InputStream stream = this.getClass().getResourceAsStream("file/Template_RH.xls");

是的,这是可能的。请参阅:Downloading a file from spring controllers

您可以尝试:Java Apache POI Excel save as PDF (我自己没有尝试过)。

关于Java Spring - 编写 Excel 文件并转换为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454286/

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