简体   繁体   English

将数据从JTable导入Excel

[英]Import data from JTable to Excel

i have code to import data from JTable to Excel like this: 我有代码将数据从JTable导入Excel,如下所示:

public void toExcel(JTable table, File file){
try {

        WritableWorkbook workbook1 = Workbook.createWorkbook(file);
        WritableSheet sheet1 = workbook1.createSheet("First Sheet", 0); 
        TableModel model = table.getModel();

        for (int i = 0; i < model.getColumnCount(); i++) {
            Label column = new Label(i, 0, model.getColumnName(i));
            sheet1.addCell(column);
        }
        int j = 0;
        for (int i = 0; i < model.getRowCount(); i++) {
            for (j = 0; j < model.getColumnCount(); j++) {
                Label row = new Label(j, i + 1, 
                        model.getValueAt(i, j).toString());
                sheet1.addCell(row);
            }
        }
        workbook1.write();
        workbook1.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


void excell(){
          toExcel(TabelPerencanaan, new File("H:\\Hasil.xlsx"));
                JOptionPane.showMessageDialog(null, "Data saved at " +
                        "'H: \\ Hasil.xlsx' successfully", "Message",
                        JOptionPane.INFORMATION_MESSAGE);

} }

But, when open file "Hasil.xlsx" always error. 但是,当打开文件“Hasil.xlsx”时总是出错。 so, that file can't opened. 所以,那个文件无法打开。 i don't know why like that. 我不知道为什么这样。 thanks 谢谢

The problem is that Java Excel API only generates spreadsheets in Excel 2000 format. 问题是Java Excel API仅生成Excel 2000格式的电子表格。 In that case, you need: 在这种情况下,您需要:

new File("H:\\Hasil.xls")

But if you really need to generate a XLSX, you can use Apache POI . 但如果您确实需要生成XLSX,则可以使用Apache POI

Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
TableModel model = table.getModel();
for (int i = 0; i < model.getColumnCount(); i++) {
    row.createCell(i).setCellValue(model.getColumnName(i));
}
for (int i = 0; i < model.getRowCount(); i++) {
    row = sheet.createRow(i + 1);
    for (int j = 0; j < model.getColumnCount(); j++) {
        row.createCell(j).setCellValue(
            model.getValueAt(i, j).toString()
        );
    }
}
FileOutputStream fileOut = new FileOutputStream("H:\\Hasil.xlsx");
wb.write(fileOut);
fileOut.close();

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

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