将包含表头的JTable数据导出到Excel文件中

问题描述 投票:0回答:2

我对此需要帮助,我无法正确解决。我想将JTable数据导出到excel文件。没有错误,但是我只获取它显示的数据,并且不包括表头。

我正在Netbeans 8.2 IDE中运行它,并且还导入了基本的jar文件。

无论如何,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
    }

我希望导出标头。谁能帮我这个忙。

java netbeans apache-poi netbeans-8
2个回答
1
投票

导出数据之前,您需要分别从jTable中导出getTableHeader()。它不会与数据一起存储,就像在Excel工作簿中一样。希望对您有所帮助:-)


1
投票

不太清楚您提供的代码中的tblData是什么。但是,如果我需要将JTable导出到Excel,那么我将按TableModel中的JTable。首先使用Excel将列名称写入TableModel.getColumnName工作表的第一行。然后使用Excel将表数据写入TableModel.getValueAt工作表的下一行。

完整示例:

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.DefaultTableModel;
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}
  };
  DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
  JTable table = new JTable(model);
  table.setModel(model);

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

 }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.