首页 > 编程知识 正文

response导出excel

时间:2023-05-06 09:11:11 阅读:237170 作者:4324

package cn.kmpro.degree.util;import java.io.IOException;import java.io.OutputStream;import java.util.List;import java.util.Map;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import javax.servlet.http.HttpServletResponse;public class ExcelUtil { /** * @功能:手工构建一个简单格式的Excel并用response返回(下载) * * @param response response对象 * @param map 数据来源 * @param strArray第一行的标题 * @param filePath文件名字 */ public static void createExcel(HttpServletResponse response, Map<String, List<String>> map, String[] strArray, String filePath) throws IOException {try { fileName = URLEncoder.encode(filePath, "utf8"); } catch (UnsupportedEncodingException e) { e.getMessage(); } OutputStream out = null; // 下面几行是为了解决文件名乱码的问题 response.setHeader("Content-Disposition", "attachment;filename=" + new String(filePath.getBytes(), "iso-8859-1")); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); out = response.getOutputStream(); // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet("sheet1"); sheet.setDefaultColumnWidth(20);// 默认列宽 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); // 创建一个居中格式 style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 添加excel title HSSFCell cell = null; for (int i = 0; i < strArray.length; i++) { cell = row.createCell((short) i); cell.setCellValue(strArray[i]); cell.setCellStyle(style); } // 第五步,写入实体数据 实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致 int i = 0; for (String str : map.keySet()) { row = sheet.createRow((int) i + 1); List<String> list = map.get(str); // 第四步,创建单元格,并设置值 for (int j = 0; j < strArray.length; j++) { String value; if (j >= list.size()){ value = ""; }else { value = list.get(j); } row.createCell((short) j).setCellValue(value); } i++; } // 第六步,将文件存到指定位置 try { wb.write(out);//将Excel用response返回 out.close(); } catch (Exception e) { e.printStackTrace(); } }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。