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

最后一个 for 循环不是表头的添加数据。在此处输入图像描述

我得到这个excel文件

在此处输入图像描述 如何获得表头?

4

5 回答 5

4

这是我从这个线程的答案中实现的 HSSF 工作簿。

我创建了一个类ExcelWriter,然后是一个方法编写器,它带有两个参数;和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();
}
}
于 2016-11-10T13:09:00.723 回答
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());           

}

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

于 2014-02-21T10:26:52.273 回答
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
于 2014-02-21T10:08:25.013 回答
0

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

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

}

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

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

}

于 2014-10-20T09:34:22.880 回答
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);
        }
    }
}
于 2016-11-13T16:23:24.303 回答