EXT结合POI导出数据到Excel表格

最近遇到了导出数据到excel的情况,刚好前台用到了EXT,就使用EXT结合POI导出数据了:

前台js代码如下:

function exportExcel(){
	 var gridpanel = grid;   //'Ext.grid.Panel'
     
     var cm=gridpanel.columns;
     //封装表格数据
     var data=[];
     var store = gridpanel.getStore();
     store.each(function(record){
         data.push(record.data);
      
     },this);
     //获取表头的dataIndex
     var headerIndex=[];
     Ext.Array.forEach( cm, function(item){
      
         if (item.xtype == "gridcolumn"&&!item.isHidden()) {
             headerIndex.push(item.dataIndex);
         }
      
     });
     //获取表头的Text
     var headText=[];
     Ext.Array.forEach( cm, function(item){
      
         if (item.xtype == "gridcolumn"&&!item.isHidden()) {
             headText.push(item.text);
         }
      
     });
     if (!Ext.fly('frmDummy')) {
         var frm = document.createElement('form');
         frm.id = 'frmDummy';
         frm.name = gridpanel.getId();
         frm.className = 'x-hidden';
         document.body.appendChild(frm);
     }
      
     Ext.Ajax.request({
         disableCaching: true ,
         url: path+'/exportExcelByExtAndPOI/exportExcel.do',
         method: 'POST',
         isUpload: true,
         form: Ext.fly('frmDummy'),
         params: {
             excleData:Ext.JSON.encode(data),
             excleHeader:Ext.JSON.encode(headerIndex),
             excleText:Ext.JSON.encode(headText)
         }
     });
}

接下来就是后台POI解析代码了:

package com.hrtel.framework.util;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/exportExcelByExtAndPOI")
public class ExportExcelByExtAndPOI {
	
	private static final Logger logger = Logger.getLogger(ExportExcelByExtAndPOI.class);
	
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response){
		logger.info("*******into method exportExcel**********");
		String excleData  = request.getParameter("excleData");
	    String excleHeader = request.getParameter("excleHeader");
	    String excleText = request.getParameter("excleText");
		JSONArray excle = JSONArray.fromObject(excleData);
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        // 解析表头
        JSONArray dataHeader = JSONArray.fromObject(excleText);
        HSSFRow headrow = sheet.createRow(0);
        for (int col = 0; col < dataHeader.size(); col++) {
            String mycell = dataHeader.getString(col);
            HSSFCell cell = headrow.createCell(col);
            // 定义单元格为字符串类型
            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            // 在单元格中输入一些内容
            cell.setCellValue(mycell);
        }
        int r=0;
        for(Object o : excle) {
            JSONObject excleObj = (JSONObject)o;
            HSSFRow row=sheet.createRow((short)r+1);
             
            //解析列
            JSONArray dataIndex = JSONArray.fromObject(excleHeader);
             
            for(int col=0;col<dataIndex.size();col++){
                String mycell=dataIndex.getString(col);
                mycell=excleObj.getString(mycell);
                HSSFCell cell = row.createCell(col);
                // 定义单元格为字符串类型
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                // 在单元格中输入一些内容
                cell.setCellValue(mycell);
                 
            }
            r++;
        };
        //通过Response把数据以Excel格式保存
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String(("test" + ".xls").getBytes("UTF-8"),
                            "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}


你可能感兴趣的:(poi,ext)