【问题标题】:Convert an excel file (xls,xlsx) for PDF将 Excel 文件 (xls,xlsx) 转换为 PDF
【发布时间】:2019-01-29 14:06:07
【问题描述】:

我必须将 Excel 文件 (xls,xlsx) 转换为 PDF,但我正在寻找更好的方法,但我不确定以下示例是否最适合我:

https://www.grapecity.com/en/blogs/use-excel-api-to-convert-spreadsheets-to-pdfs-in-java

我在这里没有找到好的帖子和答案,有人有更好的例子吗?

Java save xls file as PDF

以一种简单的方式,我只需要以更好、更简单的方式将 excel 转换为 java 中的 pdf,而无需阅读整个 excel。

我找到了这个例子,它完全符合我的需要,但是由于许可证的原因不能使用它:

https://kbdeveloper.qoppa.com/sample-java-code-to-convert-excel-to-pdf-using-jofficeconvert/

提前致谢!

【问题讨论】:

  • 好的,但是他们不希望 excel 将被“迭代”,就像您将其发送给打印机并将其另存为 pdf 时的功能一样,我过去做过但是我现在无法创建虚拟打印机
  • 您可以使用:github.com/caryyu/excel2pdfeasy 和 Apache 2 许可证
  • 非常感谢,我会测试这个!

标签: java excel


【解决方案1】:

要转换 xls:

  1. 将 xls 输入流转换为 html 输入流

  2. html 输入流转换为 pdf 输出流

  3. 这个 pdf outstream 可以写入所需的 pdf 文件,或者可以返回以供进一步使用

    public byte[] convertMsXlsBytesToPdfBytes() {
    byte[] pdfBytes = null;
    try {
        ByteArrayOutputStream pdfOutStream = new ByteArrayOutputStream();
        String fileName = "Doc Naming convention.xls";
        InputStream inputStream = new FileInputStream(fileName);
    
        //convert xls stream to html - w3 document
        org.w3c.dom.Document w3Document = ExcelToHtmlConverter.process(inputStream);
    
        //convert above w3 document to html input stream
        ByteArrayOutputStream htmlOutputStream = new ByteArrayOutputStream();
        Source xmlSource = new DOMSource(w3Document);
        Result outputTarget = new StreamResult(htmlOutputStream);
        TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
        InputStream htmlInputStream = new ByteArrayInputStream(htmlOutputStream.toByteArray());
    
        //convert html inputstream to pdf out stream
        ConverterProperties converterProperties = new ConverterProperties();
        HtmlConverter.convertToPdf(htmlInputStream, pdfOutStream, converterProperties);
    
        pdfBytes = pdfOutStream.toByteArray();
    
        //write to physical pdf file
        OutputStream out = new FileOutputStream(fileName.substring(0, fileName.indexOf(".")) + ".pdf");
        out.write(pdfBytes);
        out.close();
    } catch (Exception e) {
        // log exception details and throw custom exception
    }
    return pdfBytes; //bytes array I'm returning as per my requirement
    

    }

【讨论】:

  • 使用这个解决方案,我可以得到合并的单元格和完整的所有格式。希望对您有所帮助。
  • 这适用于 Android 吗?
【解决方案2】:

经过这么多测试,我说服他们我使用的第一个解决方案是正确的:

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
            }
    }

非常感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2011-07-29
    • 2016-06-22
    • 1970-01-01
    相关资源
    最近更新 更多