در این پست نحوه تبدیل یک کوئری را به اکسل آموزش خواهم داد و از این پست برای ایجاد وب سرویس استفاده خواهم کرد. بنابراین به موارد تکراری اشاره نکرده و صرفا روی تبدیل کوئری به اکسل تمرکز میکنیم:

برای اینکار نیاز به یک کلاس داریم به نام ResultSetToExcel که محتوای آن در زیر آمده است. وظیفه این کلاس تبدیل ResultSet به خروجی اکسل است:

package project1;

import org.apache.poi.hssf.usermodel.*;
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 org.apache.poi.hssf.util.HSSFCellUtil;

public class ResultSetToExcel {
    public static final String DATA_FORMAT = "dataFormat";
    public static final String FILL_BACKGROUND_COLOR = "fillBackgroundColor";
    public static final String FILL_FOREGROUND_COLOR = "fillForegroundColor";
    public static final String FILL_PATTERN = "fillPattern";

    private HSSFWorkbook workbook;
    private HSSFSheet sheet;
    private HSSFFont boldFont;
    private HSSFDataFormat format;
    private ResultSet resultSet;
    private FormatType[] formatTypes;

    public ResultSetToExcel(ResultSet resultSet, FormatType[] formatTypes,
                            String sheetName) {
        workbook = new HSSFWorkbook();
        this.resultSet = resultSet;
        sheet = workbook.createSheet(sheetName);
        boldFont = workbook.createFont();
        boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        format = workbook.createDataFormat();
        this.formatTypes = formatTypes;
    }

    public ResultSetToExcel(ResultSet resultSet, String sheetName) {
        this(resultSet, null, sheetName);
    }

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

    public void generate(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 = resultSetMetaData.getColumnName(i + 1);
                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();
        }
    }

    public void generate(File file) throws Exception {
        generate(new FileOutputStream(file));
    }

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

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

    private void writeCell(HSSFRow row, int col, Object value,
                           FormatType formatType, Short bgColor,
                           HSSFFont font) {
        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, DATA_FORMAT,
                                              HSSFDataFormat.getBuiltinFormat(("#,##0")));
            break;
        case FLOAT:
            cell.setCellValue(((Number)value).doubleValue());
            HSSFCellUtil.setCellStyleProperty(cell, workbook, DATA_FORMAT,
                                              HSSFDataFormat.getBuiltinFormat(("#,##0.00")));
            break;
        case DATE:
            cell.setCellValue((Timestamp)value);
            HSSFCellUtil.setCellStyleProperty(cell, workbook, DATA_FORMAT,
                                              HSSFDataFormat.getBuiltinFormat(("m/d/yy")));
            break;
        case MONEY:
            cell.setCellValue(((Number)value).intValue());
            HSSFCellUtil.setCellStyleProperty(cell, workbook, DATA_FORMAT,
                                              format.getFormat("($#,##0.00);($#,##0.00)"));
            break;
        case PERCENTAGE:
            cell.setCellValue(((Number)value).doubleValue());
            HSSFCellUtil.setCellStyleProperty(cell, workbook, DATA_FORMAT,
                                              HSSFDataFormat.getBuiltinFormat("0.00%"));
        }
        if (bgColor != null) {
            HSSFCellUtil.setCellStyleProperty(cell, workbook,
                                              FILL_FOREGROUND_COLOR, bgColor);
            HSSFCellUtil.setCellStyleProperty(cell, workbook, FILL_PATTERN,
                                              HSSFCellStyle.SOLID_FOREGROUND);
        }
    }

    public enum FormatType {
        TEXT,
        INTEGER,
        FLOAT,
        DATE,
        MONEY,
        PERCENTAGE;
    }
}
به طریق زیر از این کلاس استفاده خواهیم کرد. در این تکه کد نیز یک فایل خالی در مسیر C به نام excel-file ایجاد کرده و سپس با استفاده از متد generate اکسل را پر میکنیم:
package project1;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

@Path("/helloworld")
public class HelloWorld {
    @Context
    private UriInfo context;
    private static final String FILE_PATH = "c:\\excel-file.xls";

    public HelloWorld() {
    }

    @GET
    @Path("getFile")
    @Produces("application/vnd.ms-excel")
    public Response getFile() {

        String sqlString =
            "SELECT 'milad' as name FROM dual";

        //<create an empty excel file
		HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet firstSheet = workbook.createSheet("FIRST SHEET");
        HSSFRow rowA = firstSheet.createRow(0);
        HSSFCell cellA = rowA.createCell(0);
        cellA.setCellValue(new HSSFRichTextString(""));

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(FILE_PATH));
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }//create an empty excel file>
		
        File file = new File(FILE_PATH);
        PreparedStatement ps = null;
        try {
            Connection con = /*create a db connection*/
            ps = con.prepareStatement(sqlString);
            ResultSet resultSet = ps.executeQuery();

            ResultSetToExcel resultSetToExcel =
                new ResultSetToExcel(resultSet, new ResultSetToExcel.FormatType[] { ResultSetToExcel.FormatType.TEXT}, "sheet name");
            resultSetToExcel.generate(file);

        } catch (SQLException e) {
        } catch (NamingException e) {
        } catch (Exception e) {
        }
        ResponseBuilder response = Response.ok((Object)file);
        response.header("Content-Disposition",
                        "attachment; filename=new-excel-file.xls");
        return response.build();

    }
}

برای استفاده از این کدها شما به کتابخانه هایی نیاز دارید که یکجا در اختیارتان قرار میگیرد: دریافت حجم: 7.45 مگابایت

با تشکر
میلاد
موفق باشید