简体   繁体   English

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

[英]Read data from JTable and save it to excel (java)

I'm doing a project with other people and one of my jobs is to think how to read the data from image2 Bachelor Class detailed table and save it to excel file... this is my code so far but i don't know how to continue 我正在与其他人一起做一个项目,我的工作之一就是思考如何从image2学士班详细表中读取数据并将其保存到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)
            {

            }
        }
    }
}

I was told that i have to cycle through bachelorClassesSchedulesHolder for every tab and to take the table with index 1 (detailed table on the second picture) 有人告诉我,我必须为每个选项卡循环访问bachelorClassesSchedulesHolder并使用索引为1的表(第二张图片上的详细表)

This is the code for the tables i was told i have to use to get the information from 这是我被告知必须从中获取信息的表的代码

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

    }

the first image 第一张图片

在此处输入图片说明 the second image 第二张图片

在此处输入图片说明

Ok i have done the reading part.. but now i can't understand where am i doing wrong when exporting it to excel file.. i always get empty file and throws a lot of exceptions 好了,我已经完成了阅读部分。.但是现在我不明白将其导出到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");



        }



    }

}

I know this is an old thread. 我知道这是一个旧线程。 But I hope this could be useful for others as well. 但是我希望这对其他人也有用。
This class shall be able to generate excel file from ResultSet , JTable , and TableModel object. 此类应能够从ResultSetJTableTableModel对象生成excel文件。
The usage example is as follows: 使用示例如下:

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

TableToExcel class: 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
    }
}

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

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