exportToExcel.ResultSetToExcelTest.java Source code

Java tutorial

Introduction

Here is the source code for exportToExcel.ResultSetToExcelTest.java

Source

/*
 * Copyright (C) 2015 preto
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package exportToExcel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
//import javax.xml.crypto.Data;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ResultSetToExcelTest {

    public void Test() {

        XSSFWorkbook xlsxWorkbook = new XSSFWorkbook();
        XSSFSheet xlsSheet = xlsxWorkbook.createSheet();
        short rowIndex = 1;

        ResultSet rs = null;

        try {

            //Get the list of column names and store them as the first
            //row of the spreadsheet.
            ResultSetMetaData colInfo = rs.getMetaData();
            ArrayList<String> colNames = new ArrayList<>();
            XSSFRow titleRow = xlsSheet.createRow(rowIndex++);

            for (int i = 1; i <= colInfo.getColumnCount(); i++) {

                colNames.add(colInfo.getColumnName(i));
                titleRow.createCell((short) (i - 1)).setCellValue(new XSSFRichTextString(colInfo.getColumnName(i)));
                xlsSheet.setColumnWidth((short) (i - 1), (short) 4000);

            }

            //Save all the data from the database table rows

            while (rs.next()) {

                XSSFRow dataRow = xlsSheet.createRow(rowIndex++);

                short colIndex = 0;

                for (String colName : colNames) {
                    dataRow.createCell(colIndex++).setCellValue(new XSSFRichTextString(rs.getString(colName)));
                }
            }

            //Write to disk

            xlsxWorkbook.write(new FileOutputStream("data.xlsx"));

        } catch (SQLException | IOException e) {

            System.exit(1);

        }

    }

}