简体   繁体   English

将数据从JTable导出为PDF格式

[英]Exporting data from JTable into PDF format

I want to extract data that's inside of a JTable to a pdf file when a user clicks a button. 我想在用户单击按钮时将JTable内的数据提取到pdf文件中。

Below is my code: 下面是我的代码:

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

Your PDF generation code looks fine, Assuming u have the file getting generated on disk. 您的PDF生成代码看起来不错,假设您已经在磁盘上生成了文件。 You can use the below to download the file 您可以使用以下内容下载文件

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();   
    }  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM