将Java Swing JTable标头导出到Excel

时间:2018-01-03 11:05:25

标签: java excel swing jtable

在我的应用程序中,我已经将表格内容导出到Excel,但结果排除了表格标题。想知道如何将JTable导出到Excel包括表头?我尝试了几种方法,但仍然无法在excel中看到表头,以下是我的代码:

    defautTableModel = new DefaultTableModel(null,columnNames){
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    // the jTable row are generated dynamically.
    final JTable jTable = new JTable(defautTableModel);

    jTable.setLocation(20,60);
    jTable.setSize(950,450);
    jTable.setRowHeight(25);

    JTableHeader jTableHeader = jTable.getTableHeader();
    jTableHeader.setLocation(20,30);
    jTableHeader.setSize(950,30);
    jTableHeader.setFont(new Font(null, Font.BOLD, 16));
    jTableHeader.setResizingAllowed(true);
    jTableHeader.setReorderingAllowed(true);

    jTable.add(jTableHeader);

    JScrollPane tablePanel = new JScrollPane(jTable);
    tablePanel.setLocation(10,10);
    tablePanel.setSize(960,400);

    // export data to excel method 

    public void exportToExcel(){
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    for (int i = 0; i < defautTableModel.getRowCount(); i++) {
        Row = sheet.createRow(i);
        for (int j = 0; j < defautTableModel.getColumnCount(); j++) {
            Cell = Row.createCell(j);
            try {
                if (defautTableModel.getValueAt(i,j) != null){
                    Cell.setCellValue(defautTableModel.getValueAt(i,j).toString());
                    FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData_Output);
                    wb.write(fileOut);
                    fileOut.flush();
                    fileOut.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您只访问数据列,您需要先获取标题列。 您可以通过不同的方式实现它,或者使用方法value.var 正如ThomasEdwin在评论中提到的那样,或者使用了您为模型构造函数提供的library(data.table) setDT(df)[, c("grp", "number") := tstrsplit(place, "(?<=[A-Z])(?=[0-9])", perl = TRUE)] dcast(df, grp + time ~ number, value.var = c("data1", "data2")) 变量:getColumnName

希望有所帮助

答案 1 :(得分:0)

将带有JTable索引的Java Swing JTable标头导出到Excel

private static void writeToExcell(DefaultTableModel TabR ,TableColumnModel tableM) throws IOException {
try
{
    JFileChooser fileChooser = new JFileChooser();
   int retval = fileChooser.showSaveDialog(fileChooser);

   if (retval == JFileChooser.APPROVE_OPTION) {
       File file = fileChooser.getSelectedFile();
       if (file != null) {
           if (!file.getName().toLowerCase().endsWith(".xls")) {
               file = new File(file.getParentFile(), file.getName() + ".xls");

    @SuppressWarnings("resource")
	Workbook wb = new HSSFWorkbook();
    @SuppressWarnings("unused")
	CreationHelper createhelper = wb.getCreationHelper();
    org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
    org.apache.poi.ss.usermodel.Row row = null;

    org.apache.poi.ss.usermodel.Cell cell = null;
    

    	for (int a=0;a<TabR.getRowCount();a++)
    {
        row = sheet.createRow(a+1); /*		We create an Excel layer Row. 
        								We understand how many rows are in 
        								TabR with GetRowCount from TabR, the 
        								DefaultTableModel of the current JTable, 
        								and add one to it.*/
        
        for (int b=0;b<tableM.getColumnCount();b++) 
        {
        	cell = row.createCell(b);/*		With the GetColumnCount 
        								function of the existing JTable's 
        								TableColumnModel, we create more 
        								Column in the JTable.*/
        	
            cell.setCellValue(TabR.getValueAt(a, b).toString());	/*we give the value of the cell.	*/
        }
    }
    
    for (int c=0;c<cell.getRowIndex();c++)
    {
        row = sheet.createRow(c);
        
        for (int d=0;d<tableM.getColumnCount();d++) 
        {
             
        	cell = row.createCell(d);
            cell.setCellValue(tableM.getColumn(d).getHeaderValue().toString());
 
        }
    }
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();

       }

       }
       }

} catch (FileNotFoundException ex) {
    Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
} catch (IOException ex) {
    Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
}