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

标签 java netbeans apache-poi netbeans-8

我需要这方面的帮助,但我无法做到这一点。我想将 JTable 数据导出到 Excel 文件。没有错误,但我只获取它显示的数据,不包括表标题。

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

我的 jtable 上的数据由我的 mysql 数据库提供,我需要将其从 jtable 导出到 Excel 文件。 不管怎样,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
    }

我期待导出 header 。谁能帮我解决这个问题。

最佳答案

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

完整示例:

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

 }
}

关于java - 将 JTable 数据(包括表头)导出到 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363629/

相关文章:

java - 不可移动的警报窗口

java - JFileChooser 用于将选定的文件传递到不同类对象的参数中

java - Apache POI Java - 写入 Excel 并动态更新单元格

java - 使用 XWPFDocument 将文本附加到现有 Word 文件

java - 无法在 Windows 上打开使用 apache poi (Java) 创建的 Excel 文件

java - 替代 String.equals 进行多次比较(无枚举)

java - 有人知 Prop 有基于 Web 的可视化报告设计器的 Java 报告工具吗?

java - 使用 NodeList 遍历 XML 中的所有元素

java - 使用外部类来处理条形码扫描仪输入?

netbeans - 如何从 Mercurial 存储库获取修订号并将其粘贴到 NetBeans 资源包?