Java实现查询数据保存到Excel表中

注:需要poi.jar的支持。点击下载

package org.iisrun.customerQuery.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hg.customerQuery.Bean.DataBean;
import org.hg.customerQuery.services.CustomerQueryService;

/**
* 查询学生信息并导出到Excel中
*
* @Description Created by Jack.Dr on 2017-4-27
*/
public class ExportServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public ExportServlet() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;UTF-8");

    /*
     * 以下为生成Excel操作
     */
    // 1.创建一个workbook,对应一个Excel文件
    HSSFWorkbook wb = new HSSFWorkbook();
    // 2.在workbook中添加一个sheet,对应Excel中的一个sheet
    HSSFSheet sheet = wb.createSheet("sheet1");
    // 3.在sheet中添加表头第0行,老版本poi对excel行数列数有限制short
    HSSFRow row = sheet.createRow((int) 0);
    // 4.创建单元格,设置值表头,设置表头居中
    HSSFCellStyle style = wb.createCellStyle();
    // 居中格式
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

    // 设置表头
    HSSFCell cell = row.createCell(0);
    cell.setCellValue("STORERKEY");
    cell.setCellStyle(style);

    cell = row.createCell(1);
    cell.setCellValue("学号");
    cell.setCellStyle(style);

    cell = row.createCell(2);
    cell.setCellValue("姓名");
    cell.setCellStyle(style);

    cell = row.createCell(3);
    cell.setCellValue("年龄");
    cell.setCellStyle(style);

    cell = row.createCell(4);
    cell.setCellValue("性别");
    cell.setCellStyle(style);

    List dataset = new ArrayList();
    dataset.add(new DataBean("10001", "张三", "21", "男"));
    dataset.add(new DataBean("20002", "李四", "22", "女"));
    dataset.add(new DataBean("30003", "王五", "23", "男"));

    // 循环将数据写入Excel
    for (int i = 0; i < dataset.size(); i++) {
        row = sheet.createRow((int) i + 1);
        DataBean list = dataset.get(i);
        // 创建单元格,设置值
        row.createCell(0).setCellValue(list.getData1());
        row.createCell(1).setCellValue(list.getData2());
        row.createCell(2).setCellValue(list.getData3());
        row.createCell(3).setCellValue(list.getData4());
        row.createCell(4).setCellValue(list.getData4());
    }
    /*
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm");
    */

    String fileName = "查询学生信息";
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    wb.write(os);
    byte[] content = os.toByteArray();
    InputStream is = new ByteArrayInputStream(content);
    // 设置response参数,可以打开下载页面
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename="
            + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;

    try {
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
    out.print("{\"type\":\"success\" }");
    out.flush();
    return;
}

}

你可能感兴趣的:(Java)