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

时间:2018-05-21 17:58:34

标签: java excel spring file pdf

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

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试:

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

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

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

答案 1 :(得分:0)

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

  

项目中文件夹的路径,让我们假设您的项目   结构是src / main / java - &gt;包含一个包sructure com / aol / app /   src / main / resources - &gt;包含类似于上面的文件夹结构   com / aol / app / resources - &gt;您的文件位于何处,位于指向资源文件夹的路径下方。

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