长沙建站网站,江苏10大网站建设公司,装饰公司办公室图片,wordpress微信小程序插件背景#xff1a;
在系统开发过程中#xff0c;数据导出为 Excel 格式是一个常见的需求。然而#xff0c;由于各个开发人员的编码习惯和实现方式不同#xff0c;导致导出代码风格不一。有的人使用第三方库#xff0c;有的人则自定义实现。这种多样化不仅影响了代码的一致性…
背景
在系统开发过程中数据导出为 Excel 格式是一个常见的需求。然而由于各个开发人员的编码习惯和实现方式不同导致导出代码风格不一。有的人使用第三方库有的人则自定义实现。这种多样化不仅影响了代码的一致性也降低了可读性如下图所示给后续的维护和协作带来了很大不便。为了提升代码的规范性和可维护性我们亟需制定统一的 Excel 导出规范和最佳实践。 经过优化整理和参考网上其他作者写的文章归纳了一下较为简洁的代码。如下所示
public void exportListCommon(HttpServletResponse response, CanHistoryDataReqVO reqVO) throws IOException {String[] columnsTitle null;// 填充数据行String[][] data null;HashMapString, Object hashMap getList(new Page().setSize(-1),reqVO);if(hashMap!null){ListMapString,Object tempTitleList (ListMapString, Object) hashMap.get(title);ListHashMapString, Object tempValueList ((IPageHashMapString, Object)hashMap.get(historyDataList)).getRecords();//定义标题长度columnsTitle new String[tempTitleList.size()];//定义数据长度 new String[数据长度][标题长度];data new String[tempValueList.size()][tempTitleList.size()];for(int i 0 ; itempTitleList.size();i){//标题名赋值columnsTitle[i] (String) tempTitleList.get(i).get(paramsValue);}//给数据赋值跟列表头一一对应for (int j 0 ; j tempValueList.size();j){for (int k 0 ; k tempTitleList.size(); k){data[j][k] tempValueList.get(j).get(tempTitleList.get(k).get(paramsKey)).toString();}}}ExcelUtil.export(CanHistory,response,columnsTitle,data);} 动态导出execl数据,这段代码方便和简洁适合长期保存使用。
/*** 动态导出execl数据* param response* param columnsTitle* param data* throws IOException*/public static void export(String fileName,HttpServletResponse response, String[] columnsTitle, String[][] data) throws IOException {// 设置响应类型response.setContentType(application/vnd.openxmlformats-officedocument.spreadsheetml.sheet);response.setHeader(Content-Disposition, attachment; filenamefileName.xlsx);// 创建工作簿Workbook workbook new XSSFWorkbook();Sheet sheet workbook.createSheet(fileName);// 设置标题行Row headerRow sheet.createRow(0);for (int i 0; i columnsTitle.length; i) {Cell cell headerRow.createCell(i);cell.setCellValue(columnsTitle[i]);}// 填充数据行for (int i 0; i data.length; i) {Row dataRow sheet.createRow(i 1);for (int j 0; j data[i].length; j) {Cell cell dataRow.createCell(j);cell.setCellValue(data[i][j]);}}// 将工作簿写入响应输出流workbook.write(response.getOutputStream());workbook.close();} 测试样例 效果 觉得写的不错的朋友请点点赞❤❤❤❤❤❤❤❤