Java Apache POI Excel另存为PDF

Osc*_*ata 15 java pdf excel apache-poi playframework-2.0

如何将excel文件转换/保存到pdf?我正在使用java play framework生成一些excel文件,现在需求变为pdf.我不想重新编码.

有没有办法转换成pdf

excel我正在生成的文件来自模板; 我读了excel模板文件,写了更改,并保存为新的excel文件.这样,模板就不会改变.它包含边框,图像和其他格式.

小智 19

您需要以下Java库和关联的JAR文件才能使该程序正常工作. POI v3.8 iText v5.3.4

尝试此示例将XLS转换为PDF

下面提供了完整的Java代码,它接受Excel电子表格数据作为输入并将其转换为PDF表格数据:

 import java.io.FileInputStream;
    import java.io.*;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.ss.usermodel.*;
    import java.util.Iterator;
   import com.itextpdf.text.*;
    import com.itextpdf.text.pdf.*;

    public class excel2pdf {  
            public static void main(String[] args) throws Exception{

                    FileInputStream input_document = new FileInputStream(new File("C:\\excel_to_pdf.xls"));
                    // Read workbook into HSSFWorkbook
                    HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document); 
                    // Read worksheet into HSSFSheet
                    HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0); 
                    // To iterate over the rows
                    Iterator<Row> rowIterator = my_worksheet.iterator();
                    //We will create output PDF document objects at this point
                    Document iText_xls_2_pdf = new Document();
                    PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream("Excel2PDF_Output.pdf"));
                    iText_xls_2_pdf.open();
                    //we have two columns in the Excel sheet, so we create a PDF table with two columns
                    //Note: There are ways to make this dynamic in nature, if you want to.
                    PdfPTable my_table = new PdfPTable(2);
                    //We will use the object below to dynamically add new data to the table
                    PdfPCell table_cell;
                    //Loop through rows.
                    while(rowIterator.hasNext()) {
                            Row row = rowIterator.next(); 
                            Iterator<Cell> cellIterator = row.cellIterator();
                                    while(cellIterator.hasNext()) {
                                            Cell cell = cellIterator.next(); //Fetch CELL
                                            switch(cell.getCellType()) { //Identify CELL type
                                                    //you need to add more code here based on
                                                    //your requirement / transformations
                                            case Cell.CELL_TYPE_STRING:
                                                    //Push the data from Excel to PDF Cell
                                                     table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
                                                     //feel free to move the code below to suit to your needs
                                                     my_table.addCell(table_cell);
                                                    break;
                                            }
                                            //next line
                                    }

                    }
                    //Finally add the table to PDF document
                    iText_xls_2_pdf.add(my_table);                       
                    iText_xls_2_pdf.close();                
                    //we created our pdf file..
                    input_document.close(); //close xls
            }
    }
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您

  • 面临此问题: 提供的数据似乎位于 Office 2007+ XML 中。您正在调用 POI 中处理 OLE2 Office 文档的部分。您需要调用 POI 的不同部分来处理此数据(例如 XSSF 而不是 HSSF) (2认同)

小智 6

添加到 assylias 的答案

上面来自 assylias 的代码对我解决这个问题非常有帮助。如果您不关心生成的 PDF 看起来与 Excel pdf 导出的外观完全相同,那么 santhosh 的答案可能会很好。但是,如果您使用 Apache POI 填写 Excel 模板,然后尝试导出该模板,同时保留其外观,而不是在 iText 中编写大量代码只是为了尝试接近该外观,那么 VBS 选项是相当不错。

我将分享上面的 kotlin assylias 的 Java 版本,以防对任何人有帮助。所有解决方案的一般形式都归功于 assylias。

在爪哇中:

try {
    //create a temporary file and grab the path for it
    Path tempScript = Files.createTempFile("script", ".vbs");

    //read all the lines of the .vbs script into memory as a list
    //here we pull from the resources of a Gradle build, where the vbs script is stored
    System.out.println("Path for vbs script is: '" + Main.class.getResource("xl2pdf.vbs").toString().substring(6) + "'");
    List<String> script = Files.readAllLines(Paths.get(Main.class.getResource("xl2pdf.vbs").toString().substring(6)));

    // append test.xlsm for file name. savePath was passed to this function
    String templateFile = savePath + "\\test.xlsm";
    templateFile = templateFile.replace("\\", "\\\\");
    String pdfFile = savePath + "\\test.pdf";
    pdfFile = pdfFile.replace("\\", "\\\\");
    System.out.println("templateFile is: " + templateFile);
    System.out.println("pdfFile is: " + pdfFile);

    //replace the placeholders in the vbs script with the chosen file paths
    for (int i = 0; i < script.size(); i++) {
        script.set(i, script.get(i).replaceAll("XL_FILE", templateFile));
        script.set(i, script.get(i).replaceAll("PDF_FILE", pdfFile));
        System.out.println("Line " + i + " is: " + script.get(i));
    }

    //write the modified code to the temporary script
    Files.write(tempScript, script);

    //create a processBuilder for starting an operating system process
    ProcessBuilder pb = new ProcessBuilder("wscript", tempScript.toString());

    //start the process on the operating system
    Process process = pb.start();

    //tell the process how long to wait for timeout
    Boolean success = process.waitFor(timeout, minutes);
    if(!success) {
        System.out.println("Error: Could not print PDF within " + timeout + minutes);
    } else {
        System.out.println("Process to run visual basic script for pdf conversion succeeded.");
    }
    
} catch (Exception e) {
    e.printStackTrace();
    Alert saveAsPdfAlert = new Alert(AlertType.ERROR);
    saveAsPdfAlert.setTitle("ERROR: Error converting to pdf.");
    saveAsPdfAlert.setHeaderText("Exception message is:");
    saveAsPdfAlert.setContentText(e.getMessage());
    saveAsPdfAlert.showAndWait();  
}
Run Code Online (Sandbox Code Playgroud)

视频BS:

Option Explicit
Dim objExcel, strExcelPath, objSheet

strExcelPath = "XL_FILE"


Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Open strExcelPath
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

objSheet.ExportAsFixedFormat 0, "PDF_FILE",0, 1, 0, , , 0

objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
Run Code Online (Sandbox Code Playgroud)