public Result<Object> testreport(@RequestParam Map<String, String> params,HttpServletResponse response) throws Exception{ String filename="wenjian.xlsx"; String inFilePath="C:\\Users\\xnn\\Desktop\\附件一:高登商业生活广场用电安全分析报告.xlsx"; Result info; info=appletService.getRiskReportEnterprise(params); Map<String,Object> data = (Map<String, Object>) info.getData(); List<Map<String, Object>> rows=new ArrayList<>(); InputStream in = new FileInputStream(inFilePath); XSSFWorkbook wb = new XSSFWorkbook(in); XSSFSheet sheet = wb.getSheetAt(0); in.close(); int rowNum = 1;//模板第一行是固定标题,从第二行开始插入数据 sheet.setForceFormulaRecalculation(true);//强制执行excel中函数 // 创建一个单元格,设置其内的数据格式为字符串,并填充内容,其余单元格类同 for (Map<String, Object> row : rows) { // 获取并设置该行每一单元格的信息,该行单元格的索引从 0 开始 int cellIndex = 1;//从第二个单元格设置值,因为第一个单元格是序号函数row()-1 XSSFRow newRow = sheet.getRow(rowNum); if(newRow==null){ newRow = sheet.createRow(rowNum); } XSSFColor color = new XSSFColor(); color.setRGB(intToByteArray(getIntFromColor(68,84,106))); XSSFCellStyle style= wb.createCellStyle(); style.setFillForegroundColor(color); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); XSSFCell c2 = newRow.getCell(cellIndex++); if (c2 != null) { XSSFCellStyle originalStyle = c2.getCellStyle(); c2.setCellValue(row.get("appNumber")!=null?(String)row.get("appNumber"):null); c2.setCellStyle(originalStyle); } else { System.out.println("空!!!!!!!!!!!!!!!!!!!!!!"); c2 = newRow.createCell(cellIndex++, CellType.STRING); XSSFCellStyle originalStyle = c2.getCellStyle(); c2.setCellValue(row.get("appNumber")!=null?(String)row.get("appNumber"):null); c2.setCellStyle(originalStyle); } XSSFCell c3 = newRow.createCell(cellIndex++, CellType.STRING); // originalStyle = c3.getCellStyle(); c3.setCellValue(row.get("receiptTitle")!=null?(String)row.get("receiptTitle"):null); c3.setCellStyle(style); rowNum++; } 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); out.close(); wb.close(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * rgb转int */ private static int getIntFromColor(int Red, int Green, int Blue){ Red = (Red << 16) & 0x00FF0000; Green = (Green << 8) & 0x0000FF00; Blue = Blue & 0x000000FF; return 0xFF000000 | Red | Green | Blue; } /** * int转byte[] */ public static byte[] intToByteArray(int i) { byte[] result = new byte[4]; result[0] = (byte)((i >> 24) & 0xFF); result[1] = (byte)((i >> 16) & 0xFF); result[2] = (byte)((i >> 8) & 0xFF); result[3] = (byte)(i & 0xFF); return result; }
遇到需求一开始是想着自己填rgb颜色,但是发现还要设置字体颜色什么的比较麻烦,不如直接读取原本的文件的样式,注意要用get获取原本单元格再获取样式,create创建单元格的话,样式是空的就获取不到了。
标签:java,get,int,单元格,excel,c2,null,row From: https://www.cnblogs.com/ssbxfsrm/p/18595219