使用HSSFWorkbook将JTable导出到Excel表格中

3

你好,我正在尝试使用HSSFWorkbook将Jtable数据导出到Excel表格中。我得到了表格中的所有内容,但是没有得到表头,请问有人能帮忙吗?

这是用于获取Jtable内容的命令:

        try {
                    HSSFWorkbook fWorkbook = new HSSFWorkbook();
                    HSSFSheet fSheet = fWorkbook.createSheet("new Sheet");
                    HSSFFont sheetTitleFont = fWorkbook.createFont();
                    File file = new File("/home/kishan/NetBeansProjects/JavaChecking/src/com/verve/SwingChecking/book.xls");
                    HSSFCellStyle cellStyle = fWorkbook.createCellStyle();

                    sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                    //sheetTitleFont.setColor();
                    TableModel model = jTable1.getModel();


                    for (int i = 0; i < model.getRowCount(); i++) {
                        HSSFRow fRow = fSheet.createRow((short) i);
                        for (int j = 0; j < model.getColumnCount(); j++) {
                            HSSFCell cell = fRow.createCell((short) j);
                            cell.setCellValue(model.getValueAt(i, j).toString());
                            cell.setCellStyle(cellStyle);

                        }

                    }
    FileOutputStream fileOutputStream;
                fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
                fWorkbook.write(bos);
                bos.close();
                fileOutputStream.close();
    }catch(Exception e){

        }



for (int i = 0; i < model.getColumnCount(); i++) {
                HSSFRow fRow = fSheet.createRow((short) i);
                for(int j = 0; j < model.getColumnCount(); j++) {
                    HSSFCell cell = fRow.createCell((short) j);
                    cell.setCellValue(model.getValueAt(i, j).toString());

                    System.out.println(model.getColumnName(j));
                }
            }

最后一个循环没有添加表头数据。 enter image description here 我得到了这个Excel文件。 enter image description here 如何获取表头?

从XxxTableModel/JTable获取JTableHeader,取决于您导出的源....请确保以这种形式提出的问题在SO上无法回答。 - mKorbel
不得不(稍微)烦恼官方Oracle教程 - 如何使用表格 - mKorbel
我尝试使用最后一个for循环来获取表头,我已经附上了截图以便更清楚地理解。 - Kishan Bheemajiyani
以下是一些关于如何将JTable导出到文件的问题和答案,逻辑类似。 - mKorbel
5个回答

4
这里是我对这个主题回答中HSSF Workbook的实现方式。
我创建了一个名为ExcelWriter的类,然后定义了一个方法Writer,该方法接受两个参数:要使用的JTableFileLocation
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author oluwajayi
 */
public class ExcelWriter {

    public static void Writer (JTable jTable1, String Location) throws FileNotFoundException, IOException {

                HSSFWorkbook fWorkbook = new HSSFWorkbook();
                HSSFSheet fSheet = fWorkbook.createSheet("new Sheet");
                HSSFFont sheetTitleFont = fWorkbook.createFont();
                HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
                sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
                //sheetTitleFont.setColor();
                TableModel model = jTable1.getModel();

                //Get Header
                TableColumnModel tcm = jTable1.getColumnModel();
                HSSFRow hRow = fSheet.createRow((short) 0);
                for(int j = 0; j < tcm.getColumnCount(); j++) {                       
                   HSSFCell cell = hRow.createCell((short) j);
            cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
                   cell.setCellStyle(cellStyle);
                }

                //Get Other details
                for (int i = 0; i < model.getRowCount(); i++) {
                    HSSFRow fRow = fSheet.createRow((short) i+1);
                    for (int j = 0; j < model.getColumnCount(); j++) {
                        HSSFCell cell = fRow.createCell((short) j);
                        cell.setCellValue(model.getValueAt(i, j).toString());
                        cell.setCellStyle(cellStyle);
                    }
                }
            FileOutputStream fileOutputStream;
            fileOutputStream = new FileOutputStream(Location);
    try (BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream)) {
        fWorkbook.write(bos);
    }
            fileOutputStream.close();
}
}

3

如果要在您的表格的第一行添加列名称,可以像这样操作:

TableColumnModel tcm = jTable1.getColumnModel();
HSSFRow fRow = fSheet.createRow((short) 0);

for(int j = 0; j < tcm.getColumnCount(); j++) {

   HSSFCell cell = fRow.createCell((short) j);
   cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());           

}

您可以先运行此命令,然后从第二行开始添加表格数据。


2
你只是将TableModel中的数据写入工作簿,该模型不包含表头。请参考JTable.getTableHeader()
例如:
public class JTableExport {

public static void main(String[] args) {
    Object[] columnNames = new Object[] {"column1", "column2"};
    JTable table = new JTable(new Object[0][0], columnNames);
    TableColumnModel model = table.getTableHeader().getColumnModel();

    for (int i = 0; i < model.getColumnCount(); i++) {
        System.out.println(model.getColumn(i).getHeaderValue());
    }
}
}

这段代码会打印出以下内容。
column1
column2

我只是在尝试。你能为此更新一下小代码吗? - Kishan Bheemajiyani
我添加了示例代码。你需要创建新的HSSFCell并将它们添加到你的工作簿中,而不是使用System.out.println(..) - Markus
我现在明白了如何获取表头,但是无法将其添加到Excel表格中 :( 但是谢谢你的建议。 - Kishan Bheemajiyani
1
如果您在添加模型内容之前将表头添加到工作簿中,则需要注意第二个for循环从for(int i = 1; ...开始,否则表头将被覆盖! - Markus
如果您不能提供简单的示例,那么您的建议也没有必要。感谢您花时间进行这项工作。 - Kishan Bheemajiyani

0

for(int j=0; j

}

for(int j = 0; j < tcm.getRowCount(); j++) {

HSSFCell cell = fRow.createCell((short) j); cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());

在 for 循环中,从 0 开始遍历 tcm 的行数。在每次循环中,创建一个 HSSFCell 单元格并将其值设为 tcm 对应列的表头字符串。

}


0
我创建了这段代码:
public void Export() {

    JFileChooser save = new JFileChooser();
    save.setDialogTitle("Save as...");
    save.setFileFilter(new FileNameExtensionFilter("xls", "xlsx", "xlsm"));
    int choose = save.showSaveDialog(null);

    if(choose == JFileChooser.APPROVE_OPTION) {
        XSSFWorkbook export = new XSSFWorkbook();
        XSSFSheet sheet1 = export.createSheet("new file");
        try{
            TableModel tableModel = showQuery.getModel();

            for(int i=0; i<tableModel.getRowCount(); i++) {
                XSSFRow newRow = sheet1.createRow(i);
                for(int j=0; j<tableModel.getColumnCount(); j++) {
                    XSSFCell newCell = newRow.createCell((short) j);
                    if(i==0){
                        XSSFCellStyle style = export.createCellStyle();
                        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
                        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
                        style.setBorderBottom(BorderStyle.THIN);
                        style.setBorderTop(BorderStyle.THIN);
                        style.setBorderLeft(BorderStyle.THIN);
                        style.setBorderRight(BorderStyle.THIN);
                        newCell.setCellStyle(style);
                        newCell.setCellValue(tableModel.getColumnName(j));
                    } else {
                        XSSFCellStyle style = export.createCellStyle();
                        style.setBorderBottom(BorderStyle.THIN);
                        style.setBorderTop(BorderStyle.THIN);
                        style.setBorderLeft(BorderStyle.THIN);
                        style.setBorderRight(BorderStyle.THIN);
                        newCell.setCellStyle(style);
                    newCell.setCellValue(tableModel.getValueAt(i, j).toString());
                    }
                }
            }

            FileOutputStream otp = new FileOutputStream(save.getSelectedFile()+".xlsx");
            BufferedOutputStream bos = new BufferedOutputStream(otp);
            export.write(bos);
            bos.close();
            otp.close();

            JOptionPane.showMessageDialog(null, "Arquivo exprtado com sucesso!");
        }catch(Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接