【问题标题】:Java Spring - Writing Excel file and converting to PDFJava Spring - 编写 Excel 文件并转换为 PDF
【发布时间】:2018-10-31 10:21:06
【问题描述】:

我希望有人可以帮助我解决这个问题。我目前正在从事 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。如果有任何图书馆不能帮助我完成这项任务。

谢谢!

【问题讨论】:

    标签: java excel spring file pdf


    【解决方案1】:

    试试:

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

    是的,这是可能的。见:Downloading a file from spring controllers

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

    【讨论】:

    • 感谢您的帮助。我会尽可能地尝试一下。
    • 这确实有效。我只需要添加 .getResourceAsStream("/file/Template_RH.xls");在参数中。有趣的是,我的更新文件正在桌面中创建大声笑
    【解决方案2】:

    由于您使用的是 Spring,我建议您加载如下文件。

    项目中文件夹的路径,假设您的项目 结构是 src/main/java -> 包含一个包结构 com/aol/app/ src/main/resources -> 包含类似于上面的文件夹结构 com/aol/app/resources -> 你的文件在哪里,在指向资源文件夹的路径下方。

    public static final String FILE_CLASSPATH_RESOURCE = "com/aol/app/resources/";
    

    接下来使用 org.springframework.core.io.Resource 和 org.springframework.core.io.ClassPathResource 来加载文件,注意: 这可以是任何资源。

    Resource resource = new ClassPathResource(FILE_CLASSPATH_RESOURCE + fileName);
    

    加载资源后,您现在可以使用流生成 pdf 使用 apache poi。

    InputStream is = resource.getInputStream();
    

    由于您提到您对 Java 的了解不多,我建议您点击下面的链接,这些链接向您展示了如何处理 excel 和 pdf。

    http://www.baeldung.com/java-microsoft-excel
    https://aboullaite.me/spring-boot-excel-csv-and-pdf-view-example/
    http://www.baeldung.com/java-pdf-creation
    

    【讨论】:

    • 感谢您提供的所有信息。我去看看这个。
    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2012-11-30
    • 2014-12-03
    • 2014-09-15
    • 2019-06-03
    • 2013-10-05
    • 1970-01-01
    相关资源
    最近更新 更多