数据导出/下载
工具类:
import java.io.IOException; import java.net.URLEncoder; import sun.misc.BASE64Encoder; public class FileUtils { /** * 下载文件时,针对不同浏览器,进行附件名的编码 * * @param filename * 下载文件名 * @param agent * 客户端浏览器 * @return 编码后的下载附件名 * @throws IOException */ public static String encodeDownloadFilename(String filename, String agent) throws IOException { if (agent.contains("Firefox")) { // 火狐浏览器 filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?="; filename = filename.replaceAll("\r\n", ""); } else { // IE及其他浏览器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+"," "); } return filename; } }
/** * @Description: 查询所有分区数据,使用附件形式下载 * @return * @throws Exception * */ @Action("subareaAction_exportXls") public String exportXls() throws Exception { List<SubArea> list = subAreaService.findAll(); //通过POI将数据写入excel文件 HSSFWorkbook workbook = new HSSFWorkbook(); //空白的excel文件 //创建标签页 HSSFSheet sheet = workbook.createSheet("第一页分区数据"); //创建行 //创建标题行 HSSFRow headRow = sheet.createRow(0); //创建单元格 headRow.createCell(0).setCellValue("分区编号"); headRow.createCell(1).setCellValue("关键字"); headRow.createCell(2).setCellValue("辅助关键字"); headRow.createCell(3).setCellValue("起始号"); headRow.createCell(4).setCellValue("中止号"); headRow.createCell(5).setCellValue("省市区"); //创建数据行 for (SubArea subArea : list) { HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1); dataRow.createCell(0).setCellValue(subArea.getId()); dataRow.createCell(1).setCellValue(subArea.getKeyWords()); dataRow.createCell(2).setCellValue(subArea.getAssistKeyWords()); dataRow.createCell(3).setCellValue(subArea.getStartNum()); dataRow.createCell(4).setCellValue(subArea.getEndNum()); dataRow.createCell(5).setCellValue(subArea.getArea().getName()); } //文件名的中文问题解决(导入工具类): String fileName = "分区数据.xls"; HttpServletRequest request = ServletActionContext.getRequest(); String agent = request.getHeader("User-Agent"); fileName = FileUtils.encodeDownloadFilename(fileName, agent); //文件下载:一个流 两个头(文件MIME类型;文件打开方式(浏览器内部打开inline;附件形式下载--attachment) //从Servers项目下的web.xml中找xls对应的文件类型,比如搜索xls HttpServletResponse response = ServletActionContext.getResponse(); response.setHeader("content-type", "application/vnd.ms-excel"); response.setHeader("content-disposition", "attachment;fileName="+fileName); workbook.write(response.getOutputStream()); return NONE; }