POI之经典案例--按列名导出excel

1.首先要引入jar包(org.apache.poi的jar包最好)

2.直接上代码

public class ExportAction extends ActionSupport {
 private static final Logger logger = LoggerFactory.getActionLog(ExportAction.class);
 private static final long serialVersionUID = 1L;
 
  public void exportDatas(){
      

   List<Map<String,Object>> listBeans=XXX;//该步骤获取需要导出的list集合


   Map<String,String> cloMap=XXX.getAllCloums();//封装map为所有要到处的列,可选择


   HttpServletRequest request = super.getRequest();
   HttpServletResponse response = super.getResponse();//获取struts2的请求


   String filename="导出数据";//设置文件名


   final String userAgent = request.getHeader("USER-AGENT"); 
   try {
       if(userAgent.contains("MSIE")||userAgent.contains("Trident")){ //IE浏览器 
     filename = URLEncoder.encode(filename,"UTF-8");
        filename = StringUtils.replace(filename, "+", "%20");//替换空格
       }else if(userAgent.contains("Mozilla")){   
        filename = new String(filename.getBytes("UTF-8"), "ISO8859-1"); 
       }else{                                                
        filename = URLEncoder.encode(filename,"UTF-8");
        filename = StringUtils.replace(filename, "+", "%20");
       }
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   }

//以上为s判断浏览器兼容性
   response.setContentType("application/vnd.ms-excel;charset=utf-8");
   response.setHeader("Content-disposition", "attachment; filename="+filename+".xls");
   HSSFWorkbook wb = new HSSFWorkbook();
   HSSFSheet  sheet = wb.createSheet(filename);
   HSSFRow row1=sheet.createRow(0);

//以上创建excel工作簿


   int li=0;
   for(String value:cloMap.values()){
    row1.createCell(li).setCellValue(value);
    li++;
   }

//以上为表头


   for(int i=0;i<listBeans.size();i++){

     int col=0;
     HSSFRow row2=sheet.createRow(i+1);
     for(String key:cloMap.keySet()){
     row2.createCell(col).setCellValue(listBeans.get(i).get(key)==null ? "":String.valueOf(listBeans.get(i).get(key)));
     col++;
    }
   }

//以上为逻辑处理


   OutputStream out;
   try {
    out=response.getOutputStream();
    out.flush();
    wb.write(out);
    out.close();
   } catch (IOException e) {
    logger.info("-----Export导出异常------");
   }
         logger.info("-----end ------");
     }
}

//最后在前台通过 window.open 或者window.location.href='',发送请求



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值