Java 读取Excel模板文件,将数据填充进去,然后转成PDF文件,如何做?

Java 读取Excel模板文件,将数据填充进去,然后转成PDF文件,
有什么比较好的方式吗?
各位大佬们,推荐一下解决方式~

阅读 1.8k
1 个回答

可以用这两个库之一实现导出pdf:
https://mvnrepository.com/art...
https://mvnrepository.com/art...

在 IText 中创建 Pdf

插入文本

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextHelloWorld.pdf"));

document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);

document.add(chunk);
document.close();

使用 iText 库创建 pdf 是基于在Document中操作实现Elements接口的 对象(在 5.5.10 版本中,有 45 个实现)。

我们可以添加到文档中并使用的最小元素是Chunk,它基本上是一个带有应用字体的字符串。

此外,我们可以将Chunk与其他元素(如Paragraphs、Section等)结合起来,从而生成漂亮的文档。

插入图像

Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextImageExample.pdf"));
document.open();
Image img = Image.getInstance(path.toAbsolutePath().toString());
document.add(img);

document.close();

插入表格

首先,我们需要创建一个PdfTable对象并在构造函数中为我们的表提供一些列。

然后我们可以通过在新创建的表格对象上调用addCell方法来简单地添加新单元格。只要定义了所有必要的单元格,iText 就会创建表格行。这意味着一旦我们创建了一个包含三列的表格,并向其中添加了八个单元格,则只会显示两行,每行包含三个单元格。

看看例子:

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));

document.open();

PdfPTable table = new PdfPTable(3);
addTableHeader(table);
addRows(table);
addCustomRows(table);

document.add(table);
document.close();

创建一个包含三列和三行的新表。我们将第一行视为具有更改的背景颜色和边框宽度的表格标题:

private void addTableHeader(PdfPTable table) {
    Stream.of("column header 1", "column header 2", "column header 3")
      .forEach(columnTitle -> {
        PdfPCell header = new PdfPCell();
        header.setBackgroundColor(BaseColor.LIGHT_GRAY);
        header.setBorderWidth(2);
        header.setPhrase(new Phrase(columnTitle));
        table.addCell(header);
    });
}

第二行将包含三个单元格,只有文本,没有额外的格式:

private void addRows(PdfPTable table) {
    table.addCell("row 1, col 1");
    table.addCell("row 1, col 2");
    table.addCell("row 1, col 3");
}

我们还可以在单元格中包含图像。此外,还可以单独格式化每个单元格。

在此示例中,我们正在应用水平和垂直对齐调整:

private void addCustomRows(PdfPTable table) 
  throws URISyntaxException, BadElementException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
    Image img = Image.getInstance(path.toAbsolutePath().toString());
    img.scalePercent(10);

    PdfPCell imageCell = new PdfPCell(img);
    table.addCell(imageCell);

    PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
    horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(horizontalAlignCell);

    PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
    verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(verticalAlignCell);
}
推荐问题