简体   繁体   English

将 JTable 数据(包括表头)导出到 Excel 文件

[英]Exporting JTable Data including Table Headers to Excel File

I need help regarding this, I can't get it right.我需要这方面的帮助,我做不到。 I want to export JTable data to excel file.我想将 JTable 数据导出到 excel 文件。 There is no error but I am getting only the data it shows and does not include the table headers.没有错误,但我只得到它显示的数据,不包括表头。

I am running this in a Netbeans 8.2 IDE and had also imported the essential jar files.我在 Netbeans 8.2 IDE 中运行它,并且还导入了基本的 jar 文件。

Data on my jtable is provided by my mysql database and I need to export it from jtable to an excel file.我的 jtable 上的数据由我的 mysql 数据库提供,我需要将其从 jtable 导出到 ZBF57C906FA7D415BB66D96Z 文件。 Anyway tblData is my JTable variable name.无论如何 tblData 是我的 JTable 变量名。

private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {                                          

        FileOutputStream excelFOS = null;
        BufferedOutputStream excelBOS = null;
        XSSFWorkbook wb = null;


        JFileChooser excelFileChooser = new JFileChooser();
        excelFileChooser.setDialogTitle("Save As");
        FileNameExtensionFilter fnef = new FileNameExtensionFilter("Excel Files","xls","xlsx","ods");
        excelFileChooser.setFileFilter(fnef);
        int excelChooser = excelFileChooser.showSaveDialog(null);

        if(excelChooser == JFileChooser.APPROVE_OPTION){

            try {
                wb = new XSSFWorkbook();
                XSSFSheet sheet = wb.createSheet("Data Sheet");

                for(int i = 0; i < tblData.getRowCount(); i++){
                    XSSFRow excelRow = sheet.createRow(i);
                    for(int j = 0; j < tblData.getColumnCount(); j++){

                        XSSFCell excelCell = excelRow.createCell(j);
                        excelCell.setCellValue(tblData.getValueAt(i, j).toString());

                    }
                }   

                excelFOS = new FileOutputStream(excelFileChooser.getSelectedFile() + ".xlsx");
                excelBOS = new BufferedOutputStream(excelFOS);
                wb.write(excelBOS);
                JOptionPane.showMessageDialog(null, "Successfully saved.");

            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if(excelBOS != null){
                         excelBOS.close();
                    }
                    if(excelFOS != null){
                         excelFOS.close();
                    }
                    if(wb != null){
                         wb.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } //---- end finally
        } //---- end if condition
    }

I am expecting for the header to be exported.我期待 header 被导出。 Can anyone help me with this.谁能帮我这个。

Not really clear what tblData is in your provided code.不太清楚您提供的代码中的tblData是什么。 But If I would have the requirement to export a JTable to Excel , then I would go by TableModel of the JTable . But If I would have the requirement to export a JTable to Excel , then I would go by TableModel of the JTable . First write the column names to first row of the Excel sheet using TableModel.getColumnName .首先使用TableModel.getColumnName将列名写入Excel表的第一行。 Then write the table data to next rows of the Excel sheet using TableModel.getValueAt .然后使用TableModel.getValueAt将表数据写入Excel表的下一行。

Complete example:完整示例:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import javax.swing.JTable;
import javax.swing.table.TableModel;

class WriteJTableToExcel {

 static void exportToExcel(JTable table, String filePath) throws Exception {
  TableModel model = table.getModel();
  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet();
  Row row;
  Cell cell;

  // write the column headers
  row = sheet.createRow(0);
  for (int c = 0; c < model.getColumnCount(); c++) {
   cell = row.createCell(c);
   cell.setCellValue(model.getColumnName(c));
  }

  // write the data rows
  for (int r = 0; r < model.getRowCount(); r++) {
   row = sheet.createRow(r+1);
   for (int c = 0; c < model.getColumnCount(); c++) {
    cell = row.createCell(c);
    Object value = model.getValueAt(r, c);
    if (value instanceof String) {
     cell.setCellValue((String)value);
    } else if (value instanceof Double) {
     cell.setCellValue((Double)value);
    }
   }
  }

  FileOutputStream out = new FileOutputStream(filePath);
  workbook.write(out);
  out.close();
  workbook.close();

 }

 public static void main(String[] args) throws Exception {

  Object columnNames[] = {"Name", "Amount", "Factor"};
  Object rowData[][] = {
   {"Bob", 12.0, 3.0},
   {"Alice", 34.0, 2.5},
   {"Jack", 56.0, 2.0},
   {"John", 78.0, 1.5}
  };
  JTable table = new JTable(rowData, columnNames);

  exportToExcel(table, "./Excel.xlsx");

 }
}

you need to export the getTableHeader() from your jTable separately before you export your data.在导出数据之前,您需要分别从 jTable 导出 getTableHeader()。 It is not stored together with the data, as it is in an Excel workbook.它不与数据一起存储,因为它在 Excel 工作簿中。
Hope that helps:-)希望有帮助:-)

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

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