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='',发送请求