从JTable读取数据并将其保存到excel(java)

时间:2014-04-28 11:53:59

标签: java excel jtable

我正在和其他人一起做项目,我的一个工作就是思考如何从image2 Bachelor Class详细表中读取数据并将其保存到excel文件中... 到目前为止这是我的代码,但我不知道如何继续

    package nbu.university.excel;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;

    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;

    import nbu.university.scheduler.gui.SchedulerGui;

    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRichTextString;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;


    public class SaveToExcel extends SchedulerGui
    {



        int bachelorsTabCount = getBachelorClassesSchedulesHolder().getTabCount();
        int mastersTabCount = getMasterClassesSchedulesHolder().getTabCount();

        int bachelorsIndex = getBachelorClassesSchedulesHolder().getSelectedIndex();
        int mastersIndext = getMasterClassesSchedulesHolder().getSelectedIndex();


        public void ReadDataFromTable(JTable table, File file)
        {
            String[] colNames = {"Signature", "gr.N", "Class", "for Semester", "Horarium", "max ppl in grp",
                     "Lecturer", "Day", "Hour", "Hall type",    "requirements",}; 
            String[][] dataToBeWritten;

        for(int i = 0;i<=bachelorsTabCount; i++)
        {
            if (bachelorsIndex==1)
            {

            }
        }
    }
}

有人告诉我,我必须为每个标签循环通过bachelorClassesSchedulesHolder并使用索引1的表格(第二张图上的详细表格)

这是我告诉我必须用来从

获取信息的表的代码
private void initializeSchedulesTabsAndTabs()
    {

        Object[][] scheduleData1 = {{"", "", "", "", "", "", "", "", ""}};

        // Bachelor classes schedule array
        ArrayList<Object[][]> clasess = new ArrayList<Object[][]>();
        clasess.add(scheduleData1);

        // Add Bachelor classes schedule to classesSchedulesHolder
        // Number of Classes will be obtainable by size of array or by Options -> Settings
        for (int i = 0; i < 4; i++)
        {
            JTabbedPane classTab = new JTabbedPane();
            ShortClassScheduleTable shortClassScheduleTable = new ShortClassScheduleTable(clasess.get(0),
                                                                                          NUBER_OF_LECTURES_AT_SAME_TIME,
                                                                                          this);
            shortClassScheduleTable.setClassType(0);
            shortClassScheduleTable.setClassNumber(i);
            classTab.add(internationalization.getLabel("classLabel") + " " + (i + BACHELOR_CLASS_START_YEAR)
                         + " Week table", shortClassScheduleTable);
            ClassScheduleTable classSchedulerTable = new ClassScheduleTable(clasess.get(0));
            classSchedulerTable.setClassType(0);
            classSchedulerTable.setClassNumber(i);
            classTab.add(internationalization.getLabel("classLabel") + " " + (i + BACHELOR_CLASS_START_YEAR)
                         + " Detailed table", classSchedulerTable);

            getBachelorClassesSchedulesHolder().addTab(internationalization.getLabel("classLabel") + " "
                                                  + (i + BACHELOR_CLASS_START_YEAR), classTab);
        }

        // Add Master classes schedule to classesSchedulesHolder
        for (int i = 0; i < 4; i++)
        {
            JTabbedPane classTab = new JTabbedPane();
            ShortClassScheduleTable shortClassScheduleTable = new ShortClassScheduleTable(clasess.get(0),
                                                                                          NUBER_OF_LECTURES_AT_SAME_TIME,
                                                                                          this);
            shortClassScheduleTable.setClassType(1);
            shortClassScheduleTable.setClassNumber(i);
            // TODO
            classTab.add(internationalization.getLabel("masterClassLabel") + " "
                         + (i + MASTER_CLASS_START_YEAR) + " Week table", shortClassScheduleTable);
            classTab.add(internationalization.getLabel("masterClassLabel") + " "
                                         + (i + MASTER_CLASS_START_YEAR) + " Detailed table",
                         new ClassScheduleTable(clasess.get(0)));

            getMasterClassesSchedulesHolder().addTab(internationalization.getLabel("masterClassLabel") + " "
                                                + (i + MASTER_CLASS_START_YEAR), classTab);

            classTab.getComponent(1);
        }

    }

第一张图片

enter image description here 第二张图片

enter image description here

好的,我已经完成了阅读部分..但现在我无法理解在将其导出到excel文件时我在哪里做错了...我总是得到空文件并抛出很多例外

package nbu.university.excel;

import java.awt.Component;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
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;
import org.apache.poi.ss.usermodel.Workbook;

import nbu.university.scheduler.exception.SchedulerException;
import nbu.university.scheduler.gui.ClassScheduleTable;

public class SaveToExcel {
    private JTabbedPane schedulesHolder;
    private String techersFilePathStr;

    public SaveToExcel(JTabbedPane schedulesHolder, String techersFilePathStr) {

        if (schedulesHolder == null) {
            throw new SchedulerException("schedulesHolder cannot be null");
        }

        if(techersFilePathStr == null){
            throw new SchedulerException("techersFilePathStr cannot be null");
        }

        this.schedulesHolder = schedulesHolder;
        this.techersFilePathStr = techersFilePathStr;
    }

    public void save() throws IOException {

        JTabbedPane bachelorClassesSchedulesHolder = (JTabbedPane) schedulesHolder
                .getComponent(0);
        JTabbedPane masterClassesSchedulesHolder = (JTabbedPane) schedulesHolder
                .getComponent(1);

        List<DefaultTableModel> listDefaultTableModel = new ArrayList<DefaultTableModel>();

        for (Component component1 : schedulesHolder.getComponents()) {
            JTabbedPane classesSchedulesHolder = ((JTabbedPane) component1);

            for (Component component2 : classesSchedulesHolder.getComponents()) {

                JTabbedPane inerJtabbedPane = (JTabbedPane) component2;

                if (inerJtabbedPane.getComponentCount() > 1) {
                    Component tableComponent = ((JTabbedPane) component2)
                            .getComponentAt(1);
                    ClassScheduleTable panel = ((ClassScheduleTable) tableComponent);
                    DefaultTableModel model = panel.getDm();
                    listDefaultTableModel.add(model);
                }
            }
        }

        saveSheet(listDefaultTableModel);
    }




    private void saveSheet(List<DefaultTableModel> listDefaultTableModel) throws IOException  {
        // save

        for (DefaultTableModel model : listDefaultTableModel) {

            FileWriter saveFile = new FileWriter(techersFilePathStr);
            for(int i=0; i<model.getColumnCount();i++)
            {
                saveFile.write(model.getColumnName(i)+"\t");
            }
            saveFile.write("\n");

            for(int i=0;i<model.getColumnCount();i++)
            {
                for(int j=0;j<model.getRowCount();j++){
                    saveFile.write(model.getValueAt(i, j).toString()+"\t");
                }
                saveFile.write("\n");

            }
            saveFile.close();
            System.out.println("In saveSheetLoop");



        }



    }

}

1 个答案:

答案 0 :(得分:0)

我知道这是一个老线程。但我希望这对其他人也有用 此类应能够从ResultSetJTableTableModel对象生成excel文件。
用法示例如下:

TableToExcel tte = new TableToExcel(myTable, null, "My Table");
//optional -> tte.setCustomTitles(colTitles);
tte.generate(myFile);

TableToExcel 类:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.commons.lang.exception.NestableException;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.usermodel.contrib.HSSFCellUtil;
import org.apache.poi.ss.usermodel.contrib.CellUtil;

/**
 *
 * @author Guy Bashan, modified by Khosiawan
 */
public class TableToExcel {

    private HSSFWorkbook workbook;
    private HSSFSheet sheet;
    private HSSFFont boldFont;
    private HSSFDataFormat format;
    private ResultSet resultSet;
    private FormatType[] formatTypes;
    private List<String> colTitles;
    private JTable tbl;
    private TableModel tm;

    /**
     * Prepare an excel writer with a ResultSet data-source.
     *
     * @param rs
     * @param formatTypes - to autodetect the formatTypes, set it to null
     * @param sheetName
     */
    public TableToExcel(ResultSet rs, FormatType[] formatTypes, String sheetName) {
        initPart();
        this.resultSet = rs;
        this.formatTypes = formatTypes;
        sheet = workbook.createSheet(sheetName);
    }

    /**
     * Prepare an excel writer with a JTable data-source.
     *
     * @param tbl
     * @param formatTypes - to autodetect the formatTypes, set it to null
     * @param sheetName
     */
    public TableToExcel(JTable tbl, FormatType[] formatTypes, String sheetName) {
        initPart();
        this.tbl = tbl;
        this.formatTypes = formatTypes;
        sheet = workbook.createSheet(sheetName);
    }

    /**
     * Prepare an excel writer with a TableModel data-source.
     *
     * @param tm
     * @param formatTypes - to autodetect the formatTypes, set it to null
     * @param sheetName
     */
    public TableToExcel(TableModel tm, FormatType[] formatTypes, String sheetName) {
        initPart();
        this.tm = tm;
        this.formatTypes = formatTypes;
        sheet = workbook.createSheet(sheetName);
    }

    private void initPart() {
        workbook = new HSSFWorkbook();
        boldFont = workbook.createFont();
        boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        format = workbook.createDataFormat();
    }

    /**
     * Defining custom column titles (headers), rather than using the default
     * column name from the database.
     *
     * @param headers
     */
    public void setCustomTitles(List<String> headers) {
        this.colTitles = headers;
    }

    private FormatType getFormatType(Class _class) {
        if (_class == Integer.class || _class == Long.class) {
            return FormatType.INTEGER;
        } else if (_class == Float.class || _class == Double.class) {
            return FormatType.FLOAT;
        } else if (_class == Timestamp.class || _class == java.sql.Date.class) {
            return FormatType.DATE;
        } else {
            return FormatType.TEXT;
        }
    }

    private void generateFromResultSet(OutputStream outputStream) throws Exception {
        try {
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
                throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
                        + "Number of types: " + formatTypes.length + ". Number of columns: " + resultSetMetaData.getColumnCount());
            }
            int currentRow = 0;
            HSSFRow row = sheet.createRow(currentRow);
            int numCols = resultSetMetaData.getColumnCount();
            boolean isAutoDecideFormatTypes;
            if (isAutoDecideFormatTypes = (formatTypes == null)) {
                formatTypes = new FormatType[numCols];
            }
            for (int i = 0; i < numCols; i++) {
                String title;
                if (colTitles != null && i < colTitles.size()) {
                    title = colTitles.get(i);
                } else {
                    title = tbl != null ? tbl.getColumnName(i) : tm.getColumnName(i);
                }

                writeCell(row, i, title, FormatType.TEXT, boldFont);
                if (isAutoDecideFormatTypes) {
                    Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
                    formatTypes[i] = getFormatType(_class);
                }
            }
            currentRow++;
            // Write report rows
            while (resultSet.next()) {
                row = sheet.createRow(currentRow++);
                for (int i = 0; i < numCols; i++) {
                    Object value = resultSet.getObject(i + 1);
                    writeCell(row, i, value, formatTypes[i]);
                }
            }
            // Autosize columns
            for (int i = 0; i < numCols; i++) {
                sheet.autoSizeColumn((short) i);
            }
            workbook.write(outputStream);
        } finally {
            outputStream.close();
        }
    }

    private void generateFromTable(OutputStream outputStream) throws Exception {
        try {
            int numCols = tbl != null ? tbl.getColumnCount() : tm.getColumnCount();
            if (formatTypes != null && formatTypes.length != numCols) {
                throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
                        + "Number of types: " + formatTypes.length + ". Number of columns: " + numCols);
            }
            int currentRow = 0;
            HSSFRow row = sheet.createRow(currentRow);

            boolean isAutoDecideFormatTypes;
            if (isAutoDecideFormatTypes = (formatTypes == null)) {
                formatTypes = new FormatType[numCols];
            }
            for (int i = 0; i < numCols; i++) {
                String title;
                if (colTitles != null && i < colTitles.size()) {
                    title = colTitles.get(i);
                } else {
                    title = tbl != null ? tbl.getColumnName(i) : tm.getColumnName(i);
                }

                writeCell(row, i, title, FormatType.TEXT, boldFont);
                if (isAutoDecideFormatTypes) {
                    Class _class = tbl != null ? tbl.getColumnClass(i) : tm.getColumnClass(i);
                    formatTypes[i] = getFormatType(_class);
                }
            }
            currentRow++;
            // Write report rows
            int len = tbl != null ? tbl.getRowCount() : tm.getRowCount();
            for (int j = 0; j < len; j++) {
                row = sheet.createRow(currentRow++);
                for (int i = 0; i < numCols; i++) {
                    Object value = tbl != null ? tbl.getValueAt(j, i) : tm.getValueAt(j, i);
                    writeCell(row, i, value, formatTypes[i]);
                }
            }
            // Autosize columns
            for (int i = 0; i < numCols; i++) {
                sheet.autoSizeColumn((short) i);
            }
            workbook.write(outputStream);
        } finally {
            outputStream.close();
        }
    }

    /**
     * Generate file excel from the data-source.
     *
     * @param file - output file
     * @throws Exception
     */
    public void generate(File file) throws Exception {
        if (resultSet != null) {
            generateFromResultSet(new FileOutputStream(file));
        } else if (tbl != null || tm != null) {
            generateFromTable(new FileOutputStream(file));
        } else {
            HMOptionPane.showMsgDialog(null, "Data source is null!");
        }
    }

    private void writeCell(HSSFRow row, int col, Object value, FormatType formatType) throws NestableException {
        writeCell(row, col, value, formatType, null, null);
    }

    private void writeCell(HSSFRow row, int col, Object value, FormatType formatType, HSSFFont font) throws NestableException {
        writeCell(row, col, value, formatType, null, font);
    }

    private void writeCell(HSSFRow row, int col, Object value, FormatType formatType,
            Short bgColor, HSSFFont font) throws NestableException {
        HSSFCell cell = HSSFCellUtil.createCell(row, col, null);
        if (value == null) {
            return;
        }
        if (font != null) {
            HSSFCellStyle style = workbook.createCellStyle();
            style.setFont(font);
            cell.setCellStyle(style);
        }
        switch (formatType) {
            case TEXT:
                cell.setCellValue(value.toString());
                break;
            case INTEGER:
                cell.setCellValue(((Number) value).intValue());
                HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
                        HSSFDataFormat.getBuiltinFormat(("#,##0")));
                break;
            case FLOAT:
                cell.setCellValue(((Number) value).doubleValue());
                HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
                        HSSFDataFormat.getBuiltinFormat(("#,##0.00")));
                break;
            case DATE:
                cell.setCellValue((Timestamp) value);
                HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.DATA_FORMAT,
                        HSSFDataFormat.getBuiltinFormat(("m/d/yy")));
                break;
            case MONEY:
                cell.setCellValue(((Number) value).intValue());
                HSSFCellUtil.setCellStyleProperty(cell, workbook,
                        CellUtil.DATA_FORMAT, format.getFormat("($#,##0.00);($#,##0.00)"));
                break;
            case PERCENTAGE:
                cell.setCellValue(((Number) value).doubleValue());
                HSSFCellUtil.setCellStyleProperty(cell, workbook,
                        CellUtil.DATA_FORMAT, HSSFDataFormat.getBuiltinFormat("0.00%"));
        }
        if (bgColor != null) {
            HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_FOREGROUND_COLOR, bgColor);
            HSSFCellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_PATTERN, HSSFCellStyle.SOLID_FOREGROUND);
        }
    }

    public enum FormatType {

        TEXT,
        INTEGER,
        FLOAT,
        DATE,
        MONEY,
        PERCENTAGE
    }
}