POI实现数据导出到Excel

package com.alsi.sya;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("deprecation")
public class ExportAction extends ActionSupport implements ServletResponseAware
{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    /**
     * 导出Excel的文件名,此文件名是文档的标题
     */
    private String fileName;
    /**
     * 获取文档标题
     * @return
     */
    public String getFileName(){
        return this.fileName;
    }
    /**
     * 设置文档标题
     * @param fileName
     */
    public void setFileName(String fileName){
        this.fileName = fileName;
    }
    
    public String execute() throws Exception {
        
        HttpServletResponse response=ServletActionContext.getResponse();
        
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
        response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(getFileName(), "UTF-8"));
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        this.exportExcel(createDataList(), createMetaDataList(), getFileName()).write(response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
        return "success";
    }
    /**
     * 获取要导出的数据列表,该数据应该来源于数据库的查询结果
     * @return
     */
    public List<StudentVo> createDataList(){
        List<StudentVo> dataList = new ArrayList<StudentVo>();
        StudentVo sv1 = new StudentVo();
        sv1.setStuId("1");
        sv1.setStuName("Tom");
        sv1.setGender("M");
        StudentVo sv2 = new StudentVo();
        sv1.setStuId("2");
        sv1.setStuName("Jim");
        sv1.setGender("M");
        StudentVo sv3 = new StudentVo();
        sv1.setStuId("3");
        sv1.setStuName("Lucy");
        sv1.setGender("F");
        dataList.add(sv1);
        dataList.add(sv2);
        dataList.add(sv3);
        
        return dataList;
    }
    
    /**
     * 获取要导出数据字段名,该数据应该来源于数据库的查询结果
     * @return
     */
    public List createMetaDataList(){
        List<String> metaDataList = new ArrayList<String>();
        metaDataList.add("ID");
        metaDataList.add("NAME");
        metaDataList.add("GENDER");
        
        return metaDataList;
    }
    
    /**
     * 将查询数据库得到的数据填充到创建的Excel中
     * @param sheet 需要填充的sheet实例
     * @param startRow 开始填充的行号
     * @return 更新的行数
     */
    public int fillExcel(List dataList, Sheet sheet, int startRow, CellStyle centerstyle){
        int changeCount = 0;
        Iterator it = dataList.iterator();
        while(it.hasNext()){
            StudentVo sv = (StudentVo)it.next();
            Row row = sheet.createRow(startRow++);
            Cell cell;
            cell = row.createCell(0);  
            cell.setCellValue(sv.getStuId());  
            cell.setCellStyle(centerstyle);  
            cell = row.createCell(1);  
            cell.setCellValue(new HSSFRichTextString(sv.getStuName()));  
            cell.setCellStyle(centerstyle);  
            cell = row.createCell(2);  
            cell.setCellValue(new HSSFRichTextString(sv.getGender()));  
            cell.setCellStyle(centerstyle);
            changeCount++;
        }
        return changeCount;
    }
    
    /**
     * 将数据导出到Excel表格
     * @param metaDataList 导出字段的列表
     * @param fileName 导出Excel的文件名,或者是文件的标题
     * @return Excel的实例
     */
    public Workbook exportExcel(List dataList, List metaDataList, String fileName ) {  
        Workbook workbook = new HSSFWorkbook();// 创建一个Excel文件  
        Sheet sheet = workbook.createSheet();// 创建一个Excel的Sheet  
        // 设置字体  
        Font headfont = workbook.createFont();  
        headfont.setFontName("黑体");  
        headfont.setFontHeightInPoints((short) 22);// 字体大小  
        headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗  
        // 另一个样式  
        CellStyle headstyle = workbook.createCellStyle();  
        headstyle.setFont(headfont);  
        headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
        headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
        headstyle.setLocked(true);  
        headstyle.setWrapText(true);// 自动换行  
        // 另一个字体样式  
        Font columnHeadFont = workbook.createFont();  
        columnHeadFont.setFontName("宋体");  
        columnHeadFont.setFontHeightInPoints((short) 10);  
        columnHeadFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
        // 列头的样式  
        CellStyle columnHeadStyle = workbook.createCellStyle();  
        columnHeadStyle.setFont(columnHeadFont);  
        columnHeadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
        columnHeadStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
        columnHeadStyle.setLocked(true);  
        columnHeadStyle.setWrapText(true);  
        columnHeadStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 左边框的颜色  
        columnHeadStyle.setBorderLeft((short) 1);// 边框的大小  
        columnHeadStyle.setRightBorderColor(HSSFColor.BLACK.index);// 右边框的颜色  
        columnHeadStyle.setBorderRight((short) 1);// 边框的大小  
        columnHeadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
        columnHeadStyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色  
        // 设置单元格的背景颜色(单元格的样式会覆盖列或行的样式)  
        columnHeadStyle.setFillForegroundColor(HSSFColor.WHITE.index);  
      
        Font font = workbook.createFont();  
        font.setFontName("宋体");  
        font.setFontHeightInPoints((short) 10);  
        // 普通单元格样式  
        CellStyle style = workbook.createCellStyle();  
        style.setFont(font);  
        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 左右居中  
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);// 上下居中  
        style.setWrapText(true);  
        style.setLeftBorderColor(HSSFColor.BLACK.index);  
        style.setBorderLeft((short) 1);  
        style.setRightBorderColor(HSSFColor.BLACK.index);  
        style.setBorderRight((short) 1);  
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
        style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
        style.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
        // 另一个样式  
        CellStyle centerstyle = workbook.createCellStyle();  
        centerstyle.setFont(font);  
        centerstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中  
        centerstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中  
        centerstyle.setWrapText(true);  
        centerstyle.setLeftBorderColor(HSSFColor.BLACK.index);  
        centerstyle.setBorderLeft((short) 1);  
        centerstyle.setRightBorderColor(HSSFColor.BLACK.index);  
        centerstyle.setBorderRight((short) 1);  
        centerstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 设置单元格的边框为粗体  
        centerstyle.setBottomBorderColor(HSSFColor.BLACK.index); // 设置单元格的边框颜色.  
        centerstyle.setFillForegroundColor(HSSFColor.WHITE.index);// 设置单元格的背景颜色.  
       
          // 创建第一行,为标题行  
          Row row0 = sheet.createRow(0);  
          // 设置行高  
          row0.setHeight((short) 900);  
          // 创建第一列  
          Cell cell0 = row0.createCell(0);  
          cell0.setCellValue(new HSSFRichTextString(fileName));  
          cell0.setCellStyle(headstyle);  
          /**
           * 合并单元格
           *    第一个参数:第一个单元格的行数(从0开始)
           *    第二个参数:第二个单元格的行数(从0开始)
           *    第三个参数:第一个单元格的列数(从0开始)
           *    第四个参数:第二个单元格的列数(从0开始)
           */  
          CellRangeAddress range = new CellRangeAddress(0, 0, 0, metaDataList.size()-1);  
          sheet.addMergedRegion(range);  
          // 创建第二行,为显示时间列  
          Row row1 = sheet.createRow(1);  
          Cell cell1 = row1.createCell(0);  
          cell1.setCellValue(new HSSFRichTextString("创建时间为:"+new SimpleDateFormat("YYYY-MM-DD hh-mm-ss").format(new Date())));  
          cell1.setCellStyle(style);  
          // 合并单元格  
          range = new CellRangeAddress(1, 1, 0, metaDataList.size()-1);  
          sheet.addMergedRegion(range);  
          // 第三行,为显示字段行  
          Row row2 = sheet.createRow(2);  
          row2.setHeight((short) 750);
          Cell headCell;
          //填充字段
          for(int i=0; i<metaDataList.size(); i++){
              headCell = row2.createCell(i);  
              headCell.setCellValue(new HSSFRichTextString((String)metaDataList.get(i)));  
              headCell.setCellStyle(columnHeadStyle);
          }
          //填充具体数据到单元格
          this.fillExcel(dataList, sheet, 4, centerstyle);
          
          return workbook;  
      }
    public void setServletResponse(HttpServletResponse arg0){
        // TODO Auto-generated method stub
        
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值