遇到了个需要导出Excel的需求,经过百度查到方法在此记录一下:
public static void createExcel(List<Map<String, Object>> mapList, String filename, String title, HttpServletResponse response) { //获取数据源的 key, 用于获取列数及设置标题 Map<String, Object> map = mapList.get(0); Set<String> stringSet = map.keySet(); ArrayList<String> headList = new ArrayList<>(stringSet); //定义一个新的工作簿 XSSFWorkbook wb = new XSSFWorkbook(); //创建一个Sheet页 XSSFSheet sheet = wb.createSheet(title); //设置行高 sheet.setDefaultRowHeight((short) (2 * 256)); //为有数据的每列设置列宽 for (int i = 0; i < headList.size(); i++) { sheet.setColumnWidth(i, 8000); } //设置单元格字体样式 XSSFFont font = wb.createFont(); font.setFontName("等线"); font.setFontHeightInPoints((short) 16); //在sheet里创建第一行,并设置单元格内容为 title (标题) XSSFRow titleRow = sheet.createRow(0); XSSFCell titleCell = titleRow.createCell(0); titleCell.setCellValue(title); //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headList.size() - 1)); // 创建单元格文字居中样式并设置标题单元格居中 XSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中 titleCell.setCellStyle(cellStyle); //获得表格第二行 XSSFRow row = sheet.createRow(1); //根据数据源信息给第二行每一列设置标题 for (int i = 0; i < headList.size(); i++) { XSSFCell cell = row.createCell(i); cell.setCellValue(headList.get(i)); } XSSFRow rows; XSSFCell cells; //循环拿到的数据给所有行每一列设置对应的值 for (int i = 0; i < mapList.size(); i++) { //在这个sheet页里创建一行 rows = sheet.createRow(i + 2); //给该行数据赋值 for (int j = 0; j < headList.size(); j++) { String value; if (mapList.get(i).get(headList.get(j)) !=null){ value = mapList.get(i).get(headList.get(j)).toString(); }else { value = ""; } cells = rows.createCell(j); cells.setCellValue(value); } } try { response.setContentType("application/vnd.ms-excel"); filename = URLEncoder.encode(filename, "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" .concat(filename)); OutputStream out = response.getOutputStream(); wb.write(out); wb.close(); out.close();; } catch (IOException e) { e.printStackTrace(); } }
标签:headList,sheet,wb,get,List,Excel,filename,mapList,java From: https://www.cnblogs.com/ssbxfsrm/p/16931655.html