JAVA POI导出excel 新手

作为java新手,第一次操作java代码值得纪念。

是poi库导出excel首先得要导入poi包(java的包可真是多相比于php来讲),后面附带了poi的包供下载。

1.导入poi包到lib文件夹下面

2.导入后要先引入一下。

选中导入的jar文件鼠标右键add to build path

3.正式使用

从前台到后台的操作过程说明:

1.点击导出按钮:

window.location.href=getRootPath()+”/frontpage/export?entityCode=;

 

2.后端入口程序:

JSONObject data = resultO.getJSONObject(“data”);

            //得到要生成excl的数据集合

            JSONArray entityDataArray = data.getJSONArray(entityCode); 

            //得到列表配置数据,用于构造excl表头

            HandlerResult frontPageResult = new HandlerResult();

            frontPageResult = iFrontPageMainService.frontService(pageCode, request, frontPageResult);

            JSONObject dataO = (JSONObject)frontPageResult.getData();

            String fileNmae = dataO.getString(“pageTitle”);

            JSONArray columnArray =dataO.getJSONObject(“grid”).getJSONObject(“gridDataArea”).getJSONArray(“gridDataColumn”);

            viewExcel  =  new ViewExcel(fileNmae,entityDataArray,columnArray);

 

 

3.添加新类

ViewExcel.java

package web.controller.frontpage;
import java.io.OutputStream;  
import java.net.URLEncoder;
import java.util.Map; 

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

import org.apache.commons.lang.StringUtils;
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.springframework.web.servlet.view.document.AbstractExcelView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

import frame.platform.utils.Conver;

public class ViewExcel extends AbstractExcelView {  
    private String fileNmae;
    public ViewExcel(String fileNmae, JSONArray entityDataArray,
        JSONArray columnArray) {
        super();
        this.fileNmae = fileNmae;
        this.entityDataArray = entityDataArray;
        this.columnArray = columnArray;
    }
    public String getFileNmae() {
        return fileNmae;
    }
    public void setFileNmae(String fileNmae) {
        this.fileNmae = fileNmae;
    }
    private JSONArray entityDataArray;
    private JSONArray columnArray;

    public ViewExcel(JSONArray entityDataArray, JSONArray columnArray) {
        super();
        this.entityDataArray = entityDataArray;
        this.columnArray = columnArray;
    }
    public JSONArray getEntityDataArray() {
        return entityDataArray;
    }
    public void setEntityDataArray(JSONArray entityDataArray) {
        this.entityDataArray = entityDataArray;
    }
    public JSONArray getColumnArray() {
        return columnArray;
    }
    public void setColumnArray(JSONArray columnArray) {
        this.columnArray = columnArray;
    }
    @Override  
    protected void buildExcelDocument(Map<String, Object> obj,  
            HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)  
            throws Exception { 
        HSSFSheet sheet = workbook.createSheet("list");    
        sheet.setDefaultColumnWidth((short) 12);    
        //头数据处理
        StringBuffer  marketXml = new StringBuffer();
         for (int i = 0; i < columnArray.size(); i++) {
                JSONObject jo = (JSONObject)columnArray.get(i);
                if(!jo.getBooleanValue("isHidden")){
                     marketXml.append(jo.get("columnTitle"));
                     HSSFCell cell = getCell(sheet, 0, i-1);    
                     setText(cell, (String)jo.getString("columnTitle"));
                     HSSFCellStyle dateStyle = workbook.createCellStyle();    
                }
         }
         //填充表格数据
         StringBuffer  marketXml1 = new StringBuffer();
         for (int i = 0; i < entityDataArray.size(); i++) {
             JSONObject jo1 = (JSONObject)entityDataArray.get(i);
             for (int j = 0; j < columnArray.size(); j++) {
                    JSONObject colArr = (JSONObject)columnArray.get(j);
                    if(!colArr.getBooleanValue("isHidden")){
                        //显示的栏目名称
                        HSSFCell cellData = getCell(sheet, i+1, j-1);
                        cellData.setCellValue(Conver.convertNull(jo1.get(colArr.get("columnCode"))));
                    }
         }
         }
         //填充表格数据
        String filename = fileNmae+".xls";//设置下载时客户端Excel的名称     
        filename = encodeFilename(filename, request);//处理中文文件名  
        response.setContentType("application/vnd.ms-excel");     
        response.setHeader("Content-disposition", "attachment;filename=" + filename);     
        OutputStream ouputStream = response.getOutputStream();     
        workbook.write(ouputStream);     
        ouputStream.flush();     
        ouputStream.close();     
    }
    /**  
     * 设置下载文件中文件的名称  
     *   
     * @param filename  
     * @param request  
     * @return  
     */    
    public static String encodeFilename(String filename, HttpServletRequest request) {    
      /**  
       * 获取客户端浏览器和操作系统信息  
       * 在IE浏览器中得到的是:User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)  
       * 在Firefox中得到的是:User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6  
       */    
      String agent = request.getHeader("USER-AGENT");    
      try {    
        if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {    
          String newFileName = URLEncoder.encode(filename, "UTF-8");    
          newFileName = StringUtils.replace(newFileName, "+", "%20");    
          if (newFileName.length() > 150) {    
            newFileName = new String(filename.getBytes("GB2312"), "ISO8859-1");    
            newFileName = StringUtils.replace(newFileName, " ", "%20");    
          }    
          return newFileName;    
        }    
        if ((agent != null) && (-1 != agent.indexOf("Mozilla")))    
        return MimeUtility.encodeText(filename, "UTF-8", "B");    
        return filename;    
      } catch (Exception ex) {    
        return filename;    
      }    
    }
}

View Code

这样就可以跑了:看效果

 

版权声明:本文为miketwais原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/miketwais/articles/JAVA.html