gpt4 book ai didi

java - 将 JTable 中的数据导出为 PDF 格式

转载 作者:行者123 更新时间:2023-12-02 02:53:45 25 4
gpt4 key购买 nike

我想在用户单击按钮时将 JTable 内部的数据提取到 pdf 文件。

下面是我的代码:

public void actionPerformed(ActionEvent e) {
try {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream("table.pdf"));
doc.open();
PdfPTable pdfTable = new PdfPTable(table.getColumnCount());
//adding table headers
for (int i = 0; i < table.getColumnCount(); i++) {
pdfTable.addCell(table.getColumnName(i));
}
//extracting data from the JTable and inserting it to PdfPTable
for (int rows = 0; rows < table.getRowCount() - 1; rows++) {
for (int cols = 0; cols < table.getColumnCount(); cols++) {
pdfTable.addCell(table.getModel().getValueAt(rows, cols).toString());
}
}
doc.add(pdfTable);
doc.close();
System.out.println("done");
} catch (DocumentException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}

最佳答案

您的 PDF 生成代码看起来不错,假设您在磁盘上生成了文件。您可以使用以下方式下载文件

import java.io.*;  
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class ExportJtable extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/pdf");
PrintWriter out = response.getWriter();
String filename = "table.pdf";
String filepath = "/user/home";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");

FileInputStream fileInputStream = new FileInputStream(filepath + filename);

int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
}
}

关于java - 将 JTable 中的数据导出为 PDF 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57091311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com