數據導出/下載
阿新 • • 發佈:2017-08-29
net tex string log color turn urlencode 解決 adr
工具類:
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; }
數據導出/下載