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> listBeans=XXX;//该步骤获取需要导出的list集合


   Map 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

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



你可能感兴趣的:(POI)