You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将jTable中选中的行数据导出为PDF文档

JTable选中行提取数据并生成PDF实现方案

1. 获取JTable选中行的数据

先判断是否有选中行,再通过行索引提取对应列的数据,存储到集合里方便后续使用:

// 假设你的JTable实例名为table
int selectedRow = table.getSelectedRow();
if (selectedRow == -1) {
    JOptionPane.showMessageDialog(null, "请先选中一行数据");
    return;
}

// 存储提取到的行数据
Map<String, String> rowData = new HashMap<>();
rowData.put("Name", table.getValueAt(selectedRow, 0).toString());
rowData.put("Book Borrowed", table.getValueAt(selectedRow, 1).toString());
rowData.put("Date of Return", table.getValueAt(selectedRow, 2).toString());
rowData.put("Date Today", table.getValueAt(selectedRow, 3).toString());

2. 使用iText生成PDF

引入依赖(Maven)

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

生成PDF的核心代码

private void generatePDF(Map<String, String> rowData) {
    Document document = new Document();
    try {
        // 指定PDF保存路径(示例为桌面)
        String savePath = System.getProperty("user.home") + "/Desktop/borrow_record.pdf";
        PdfWriter.getInstance(document, new FileOutputStream(savePath));
        
        document.open();
        // 添加标题
        document.add(new Paragraph("图书借阅记录", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 18)));
        document.add(new Paragraph("\n"));
        
        // 写入提取的行数据
        for (Map.Entry<String, String> entry : rowData.entrySet()) {
            document.add(new Paragraph(String.format("%s: %s", entry.getKey(), entry.getValue())));
        }
        
        JOptionPane.showMessageDialog(null, "PDF已生成,保存至桌面");
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "PDF生成失败:" + e.getMessage());
    } finally {
        if (document.isOpen()) {
            document.close();
        }
    }
}

3. 整合到触发事件(比如按钮点击)

把获取数据和生成PDF的逻辑绑定到按钮点击事件:

JButton generateBtn = new JButton("生成PDF");
generateBtn.addActionListener(e -> {
    // 获取选中行数据
    int selectedRow = table.getSelectedRow();
    if (selectedRow == -1) {
        JOptionPane.showMessageDialog(null, "请先选中一行数据");
        return;
    }

    Map<String, String> rowData = new HashMap<>();
    rowData.put("Name", table.getValueAt(selectedRow, 0).toString());
    rowData.put("Book Borrowed", table.getValueAt(selectedRow, 1).toString());
    rowData.put("Date of Return", table.getValueAt(selectedRow, 2).toString());
    rowData.put("Date Today", table.getValueAt(selectedRow, 3).toString());
    
    // 生成PDF
    generatePDF(rowData);
});

补充说明

  • 如果你的JTable列顺序和示例不同,需要调整getValueAt方法的第二个参数(列索引)。
  • 可以通过iText的API调整PDF样式,比如添加表格、修改字体/颜色、调整行距等。
  • 若偏好Apache PDFBox,核心逻辑一致,仅API调用不同,iText更适合快速生成简单结构化文档。

内容的提问来源于stack exchange,提问作者Silent Romance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 15:11:00