如何用DataList实现某一列如果超过特定长度就自动换行

博客展示了一段ASP代码,包含一个DataList控件,设置了宽度和单元格间距。在ItemTemplate中,对FileName数据项进行处理,根据其长度进行不同操作,如替换特殊字符、截取字符串等。
<asp:datalist id="DataList1" runat="server" Width="280px" CellSpacing="5">
 <ItemTemplate>
           <%#DataBinder.Eval(Container.DataItem,"FileName").ToString().Length>16?DataBinder.Eval
           (Container.DataItem,"FileName").ToString().Replace("/n","").Replace("<","&lt;").Replace
           (">","&gt").Replace("/r","<br>").Replace(" ","&nbsp;").Substring(0,16):DataBinder.Eval
           (Container.DataItem,"FileName").ToString()%>
 </ItemTemplate>
</asp:datalist>
java,excel导出 在导出动态列中新增一行,内容为:“标准(nationalStandardCode)",数据取自如下代码: // 查询国标 String nationalStandardCode = iqcInspectDelegate.getNationalStandardCode(); // 国标编码 这一行需合并动态列长度的单元格,左侧固定列仍然要与动态列对齐 要求:必须在我原本的代码上进行修改,不要封装方法,不要给出伪代码,必须要是完整且详细的代码 我原本的代码如下: @Override public void exportInspectDelegateReport(String id, HttpServletResponse response) { try { // 1. 获取数据 IqcInspectDelegate iqcInspectDelegate = getById(id); // 委托单 // 准备映射 // 报告名称 Map<String, String> reportNameMap = ListUtils.convertListToMap( dictService.getDictItems("iqc_inspect_report_name"), DictModel::getValue, DictModel::getText); // 记录表编号 Map<String, String> recordNumberMap = ListUtils.convertListToMap( dictService.getDictItems("iqc_inspect_record_number"), DictModel::getValue, DictModel::getText); // 查询供应商名称、物料名称、接收单编号 String arrivalId = iqcInspectDelegate.getArrivalId(); // 到货单主键 IqcArrivalReportForm arrivalReportForm = arrivalReportFormMapper.selectById(arrivalId); // 到货单 // 设置默认值 String vendorName = arrivalReportForm != null ? StringUtils.defaultString(arrivalReportForm.getVendor(), "") : ""; String specification = arrivalReportForm != null ? StringUtils.defaultString(arrivalReportForm.getSpecification(), "") : ""; // 翻译检测人员、审核人 String testByName = sysUserService.getNameByUserName(iqcInspectDelegate.getTestBy()) != null ? sysUserService.getNameByUserName(iqcInspectDelegate.getTestBy()) : ""; String reviewerName = sysUserService.getNameByUserName(iqcInspectDelegate.getReviewer()) != null ? sysUserService.getNameByUserName(iqcInspectDelegate.getReviewer()) : ""; // 翻译牌号 String pointAssignName = ""; String pointAssignId = iqcInspectDelegate.getPointAssignId(); // 牌号主键 IqcPointAssign iqcPointAssign = pointAssignService.getById(pointAssignId); // 牌号 if (iqcPointAssign != null) { pointAssignName = StringUtils.defaultString(iqcPointAssign.getPointName(), ""); } // 获取报告名称 String reportName = reportNameMap.get(iqcInspectDelegate.getExperimentalProject()); reportName = StringUtils.defaultString(reportName, ""); // 获取记录表编号 String recordNumber = recordNumberMap.get(iqcInspectDelegate.getExperimentalProject()); recordNumber = StringUtils.defaultString(recordNumber, ""); // 处理日期字段 String testTimeStr = ""; if (iqcInspectDelegate.getTestTime() != null) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); testTimeStr = sdf.format(iqcInspectDelegate.getTestTime()); } // 查询国标 String nationalStandardCode = iqcInspectDelegate.getNationalStandardCode(); // 国标编码 QueryWrapper<NationalStandardMain> standardMainQueryWrapper = new QueryWrapper<>(); standardMainQueryWrapper.eq("national_standard_code", nationalStandardCode); standardMainQueryWrapper.eq("is_deleted", 0); List<NationalStandardMain> standardMainList = standardMainService.list(standardMainQueryWrapper); List<NationalStandardItem> standardItemList = new ArrayList<>(); if (!CollectionUtils.isEmpty(standardMainList)) { NationalStandardMain nationalStandardMain = standardMainList.get(0); // 国标主表 String nationalStandardMainId = nationalStandardMain.getId(); // 国标主键 QueryWrapper<NationalStandardItem> standardItemQueryWrapper = new QueryWrapper<>(); standardItemQueryWrapper.eq("main_id", nationalStandardMainId); standardItemQueryWrapper.eq("is_deleted", 0); standardItemList = standardItemService.list(standardItemQueryWrapper); } // 查询试样 QueryWrapper<IqcDelegateSample> sampleQueryWrapper = new QueryWrapper<>(); sampleQueryWrapper.eq("delegate_id", id); // 委托单主键 sampleQueryWrapper.eq("is_deleted", 0); List<IqcDelegateSample> sampleList = delegateSampleService.list(sampleQueryWrapper); List<Map<String, Object>> sampleDataList = new ArrayList<>(); // 用于Excel导出的数据 if (!CollectionUtils.isEmpty(sampleList)) { for (IqcDelegateSample sample : sampleList) { String sampleId = sample.getId(); // 试样主键 // 查询试验数据 QueryWrapper<IqcDelegateValue> delegateValueQueryWrapper = new QueryWrapper<>(); delegateValueQueryWrapper.eq("sample_id", sampleId); delegateValueQueryWrapper.eq("is_deleted", 0); List<IqcDelegateValue> valueDataList = delegateValueService.list(delegateValueQueryWrapper); Map<String, Object> sampleData = new HashMap<>(); // 添加试样基本信息 sampleData.put("sampleCode", StringUtils.defaultString(sample.getSampleCode(), "")); sampleData.put("sampleName", StringUtils.defaultString(sample.getSampleName(), "")); if (!CollectionUtils.isEmpty(valueDataList)) { for (IqcDelegateValue valueData : valueDataList) { // 获取试验项目信息 String standardAssociation = valueData.getStandardAssociation(); if (StringUtils.isNotBlank(standardAssociation)) { // 查找对应的国标项 for (NationalStandardItem item : standardItemList) { if ((item.getStandardContent()+item.getStandardValue()).equals(standardAssociation)) { sampleData.put( StringUtils.defaultString(item.getStandardContent()+item.getStandardValue(), ""), StringUtils.defaultString(valueData.getDataValue(), "") ); break; } } } } } sampleDataList.add(sampleData); } } // 2. 创建Excel Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建通用边框样式 CellStyle borderStyle = workbook.createCellStyle(); borderStyle.setBorderTop(BorderStyle.THIN); borderStyle.setBorderBottom(BorderStyle.THIN); borderStyle.setBorderLeft(BorderStyle.THIN); borderStyle.setBorderRight(BorderStyle.THIN); // 标题样式 CellStyle titleStyle = workbook.createCellStyle(); Font titleFont = workbook.createFont(); titleFont.setBold(true); titleFont.setFontHeightInPoints((short) 16); titleStyle.cloneStyleFrom(borderStyle); // 继承边框 titleStyle.setFont(titleFont); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 项目名称样式 CellStyle projectStyle = workbook.createCellStyle(); Font projectFont = workbook.createFont(); projectFont.setBold(true); projectFont.setFontHeightInPoints((short) 14); projectStyle.cloneStyleFrom(borderStyle); // 继承边框 projectStyle.setFont(projectFont); projectStyle.setAlignment(HorizontalAlignment.CENTER); projectStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 创建记录表编号 - 居右 CellStyle recordStyle = workbook.createCellStyle(); recordStyle.cloneStyleFrom(projectStyle); // 继承项目样式 recordStyle.setAlignment(HorizontalAlignment.RIGHT); // 设置居右 // 表头样式 CellStyle headerStyle = workbook.createCellStyle(); Font headerFont = workbook.createFont(); headerFont.setBold(true); headerFont.setFontHeightInPoints((short) 12); headerStyle.setFont(headerFont); headerStyle.cloneStyleFrom(borderStyle); // 继承边框 headerStyle.setAlignment(HorizontalAlignment.CENTER); headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); headerStyle.setWrapText(true); // 自动换行 // 数据样式 CellStyle dataStyle = workbook.createCellStyle(); Font dataFont = workbook.createFont(); dataFont.setFontHeightInPoints((short) 11); dataStyle.setFont(dataFont); dataStyle.cloneStyleFrom(borderStyle); // 继承边框 dataStyle.setAlignment(HorizontalAlignment.CENTER); dataStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 信息行样式 CellStyle infoStyle = workbook.createCellStyle(); Font infoFont = workbook.createFont(); infoFont.setFontHeightInPoints((short) 11); infoStyle.setFont(infoFont); infoStyle.cloneStyleFrom(borderStyle); // 继承边框 infoStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 创建标题行 // 公司名称 Row titleRow = sheet.createRow(0); titleRow.setHeight((short) 500); Cell titleCell = titleRow.createCell(0); titleCell.setCellValue("眉山中车制动科技股份有限公司"); titleCell.setCellStyle(titleStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, standardItemList.size() + 3)); // 报告名称行 Row projectRow = sheet.createRow(1); projectRow.setHeight((short) 400); Cell projectCell = projectRow.createCell(0); projectCell.setCellValue(reportName); projectCell.setCellStyle(projectStyle); sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, standardItemList.size() + 3)); // 记录表编号行 - 居右 Row recordRow = sheet.createRow(2); recordRow.setHeight((short) 400); Cell recordCell = recordRow.createCell(0); recordCell.setCellValue(recordNumber); recordCell.setCellStyle(recordStyle); sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, standardItemList.size() + 3)); // 信息行 Row infoRow = sheet.createRow(3); infoRow.setHeight((short) 400); // 供应商信息 Cell vendorCell = infoRow.createCell(0); vendorCell.setCellValue("供应商:" + vendorName); vendorCell.setCellStyle(infoStyle); // 试验日期 Cell dateLabelCell = infoRow.createCell(2); dateLabelCell.setCellValue("试验日期:"); dateLabelCell.setCellStyle(infoStyle); Cell dateValueCell = infoRow.createCell(3); dateValueCell.setCellValue(testTimeStr); dateValueCell.setCellStyle(infoStyle); // 报告编号 Cell reportLabelCell = infoRow.createCell(4); reportLabelCell.setCellValue("报告编号:"+iqcInspectDelegate.getDelegateCode()); reportLabelCell.setCellStyle(infoStyle); Cell reportValueCell = infoRow.createCell(5); reportValueCell.setCellStyle(infoStyle); // 合并单元格 sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 1)); // 供应商 sheet.addMergedRegion(new CellRangeAddress(3, 3, 2, 3)); // 试验日期 sheet.addMergedRegion(new CellRangeAddress(3, 3, 4, standardItemList.size() + 3)); // 报告编号 Row headerRow1 = sheet.createRow(4); headerRow1.setHeight((short) 400); Row headerRow2 = sheet.createRow(5); headerRow2.setHeight((short) 400); // 固定列标题 String[] fixedHeaders = {"试样名称", "牌号", "规格", "试样编号"}; for (int i = 0; i < fixedHeaders.length; i++) { // 第一行创建固定列单元格 Cell cell1 = headerRow1.createCell(i); cell1.setCellValue(fixedHeaders[i]); cell1.setCellStyle(headerStyle); // 第二行创建空单元格 Cell cell2 = headerRow2.createCell(i); cell2.setCellStyle(headerStyle); // 合并固定列 sheet.addMergedRegion(new CellRangeAddress(4, 5, i, i)); } // 动态列标题 for (int j = 0; j < standardItemList.size(); j++) { int colIndex = fixedHeaders.length + j; // 第一行:内容 Cell contentCell = headerRow1.createCell(colIndex); contentCell.setCellValue(standardItemList.get(j).getStandardContent()); contentCell.setCellStyle(headerStyle); // 第二行:范围 Cell valueCell = headerRow2.createCell(colIndex); // 范围格式需转换 String convertedStandardValue = convertStandardValue(iqcInspectDelegate.getExperimentalProject(), standardItemList.get(j).getStandardValue()); valueCell.setCellValue(convertedStandardValue); valueCell.setCellStyle(headerStyle); } for (int i = 0; i < sampleDataList.size(); i++) { Map<String, Object> sampleData = sampleDataList.get(i); Row dataRow = sheet.createRow(6 + i); dataRow.setHeight((short) 400); // 固定列数据 Cell sampleNameCell = dataRow.createCell(0); sampleNameCell.setCellValue(sampleData.get("sampleName").toString()); sampleNameCell.setCellStyle(dataStyle); Cell pointAssignCell = dataRow.createCell(1); pointAssignCell.setCellValue(pointAssignName); pointAssignCell.setCellStyle(dataStyle); Cell specificationCell = dataRow.createCell(2); specificationCell.setCellValue(specification); specificationCell.setCellStyle(dataStyle); Cell sampleCodeCell = dataRow.createCell(3); sampleCodeCell.setCellValue(sampleData.get("sampleCode").toString()); sampleCodeCell.setCellStyle(dataStyle); // 动态列数据 for (int j = 0; j < standardItemList.size(); j++) { String itemKey = standardItemList.get(j).getStandardContent() + standardItemList.get(j).getStandardValue(); Object value = sampleData.get(itemKey); Cell valueCell = dataRow.createCell(4 + j); valueCell.setCellValue(value != null ? value.toString() : ""); valueCell.setCellStyle(dataStyle); } } int remarkRowNum = 6 + sampleDataList.size(); Row remarkRow = sheet.createRow(remarkRowNum); remarkRow.setHeight((short) 400); Cell remarkCell = remarkRow.createCell(0); remarkCell.setCellValue("备注:" + iqcInspectDelegate.getRemark()); remarkCell.setCellStyle(infoStyle); sheet.addMergedRegion(new CellRangeAddress( remarkRowNum, remarkRowNum, 0, standardItemList.size() + 3)); int lastRow = remarkRowNum + 1; Row footerRow = sheet.createRow(lastRow); footerRow.setHeight((short) 400); Cell footerCell = footerRow.createCell(0); footerCell.setCellValue("分析:" + testByName + " 审批人:" + reviewerName); footerCell.setCellStyle(infoStyle); sheet.addMergedRegion(new CellRangeAddress( lastRow, lastRow, 0, standardItemList.size() + 3)); CellStyle verticalCenterStyle = workbook.createCellStyle(); verticalCenterStyle.cloneStyleFrom(headerStyle); verticalCenterStyle.setVerticalAlignment(VerticalAlignment.CENTER); for (int i = 0; i < fixedHeaders.length; i++) { headerRow1.getCell(i).setCellStyle(verticalCenterStyle); } // 设置列宽 sheet.setColumnWidth(0, 4000); // 试样名称 sheet.setColumnWidth(1, 4000); // 牌号 sheet.setColumnWidth(2, 3000); // 规格 sheet.setColumnWidth(3, 4000); // 试样编号 // 动态列宽度 for (int i = 0; i < standardItemList.size(); i++) { sheet.setColumnWidth(4 + i, 4000); // 每个动态列 } // 3. 为所有单元格添加边框 int lastRowNum = sheet.getLastRowNum(); int lastCellNum = standardItemList.size() + 3; for (int r = 0; r <= lastRowNum; r++) { Row row = sheet.getRow(r) != null ? sheet.getRow(r) : sheet.createRow(r); for (int c = 0; c <= lastCellNum; c++) { Cell cell = row.getCell(c) != null ? row.getCell(c) : row.createCell(c); // 保留原有样式基础上添加边框 CellStyle currentStyle = cell.getCellStyle(); CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(currentStyle); newStyle.setBorderTop(BorderStyle.THIN); newStyle.setBorderBottom(BorderStyle.THIN); newStyle.setBorderLeft(BorderStyle.THIN); newStyle.setBorderRight(BorderStyle.THIN); cell.setCellStyle(newStyle); } } response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=inspectDelegateReport.xlsx"); workbook.write(response.getOutputStream()); workbook.close(); } catch (Exception e) { log.error("导出Excel时发生错误", e); throw new RuntimeException("导出Excel失败: " + e.getMessage()); } }
最新发布
09-11
String tableName =req.getTableName(); Integer userId= TSysUser.getUserId(); Map<String, Object> defaultLabelMap=req.getDefaultLabelMap(); String bussCode=req.getBussCode(); List<Map<String,Object>> keyValueMap=req.getKeyValueMap(); ExcelTplVO excelTplVO = new ExcelTplVO(); // 0、数据初始化:导入列,表码元数据,表码数据,表显示名称,单元格样式 List<ImportRule> ruleList = metaDataGetBPO.getRuleList(tableName); List<Column> importColumnList = metaDataGetBPO.getImportColumnSortList(userId, tableName, defaultLabelMap, ruleList); List<CodeMeta> codeMetaList = metaDataGetBPO.getCodeMetaList(importColumnList, ruleList); List<CodeData> codeDataList = metaDataGetBPO.getCodeDataList(codeMetaList, userId, bussCode, tableName); String tableLabel = metaDataGetBPO.getDbTable(tableName).getTableLabel(); HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(excelTemplateBPO.getHeadStyle(), excelTemplateBPO.getContentStyle()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ExcelWriter excelWriter = EasyExcel.write(outputStream).build()) { // 1.数据表输出 // 1.1 数据表头 List<List<String>> list = mainHead(importColumnList, codeMetaList, req.getDyncCols()); WriteSheet writeSheet = EasyExcel.writerSheet(0).sheetName(tableLabel). registerWriteHandler(new ExcelCellStyleHandler()). registerWriteHandler(horizontalCellStyleStrategy). registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()). registerWriteHandler(new DropDownSheetWriteHandler(codeMetaList)). registerWriteHandler(new CustomCommentWriteHandler(codeMetaList)). head(list).build(); // 1.2 数据表 boolean isAdd = false; if (keyValueMap == null) { isAdd = true; } ExcelOutService excelOutService = excelOutServiceFactory.getService(tableName, codeDataList, isAdd); List<List<Object>> mainDataList = excelOutService.mainData(tableName, importColumnList, codeDataList, keyValueMap); if(!isAdd){ HandlerDataVo vo = new HandlerDataVo(); vo.setTableName(tableName); vo.setDataList(mainDataList); vo.setImportColumnList(importColumnList); vo.setCodeDataList(codeDataList); vo.setCodeMetaList(codeMetaList); mainDataList = excelOutTranComposeService.outTran(vo); } excelWriter.write(mainDataList, writeSheet); // 2、表码表写入 Integer index = 1; //说明配置页 index = writeRemarkSheet(index, tableName, excelWriter); // index = excelOutExtraFactoryService.addSheet(tableName, req.getDyncCols(), excelWriter, index, horizontalCellStyleStrategy); Set<String> processedSheets = new HashSet<>(); for (CodeData codeData : codeDataList) { // A01 数据太大而且涉及权限,不加 CodeMeta codeMeta=codeData.getCodeMeta(); if("A01".equals(codeMeta.getTableName())){ continue; } String tableLabelOne = codeData.getCodeMeta().getTableLabel(); // 如果 tableLabelOne 包含 "、",则替换为 "_" if (tableLabelOne.contains("/")) { tableLabelOne = tableLabelOne.replace("/", "_"); } List<List<String>> bmList = codeHead(); List<List<String>> dataList = codeDataList(codeData); ExcelOutExtraService excelOutExtraService = excelOutExtraFactoryService.getService(tableName,codeMeta.getTableName()); if(excelOutExtraService!=null){ OutExtraDataVo vo= new OutExtraDataVo(); vo.setTableName(tableName); vo.setBussCode(bussCode); excelOutExtraService.init(); bmList=excelOutExtraService.mainHead(vo); dataList= excelOutExtraService.mainData(vo); } // 2.1 表头 if (!processedSheets.contains(tableLabelOne)) { WriteSheet writeSheetOne = EasyExcel.writerSheet(index++).sheetName(tableLabelOne) .registerWriteHandler(horizontalCellStyleStrategy) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .registerWriteHandler(new ExcelCellStyleHandler()) .head(bmList).build(); processedSheets.add(tableLabelOne); // 2.2 数据插入 excelWriter.write(dataList, writeSheetOne); } } } catch (Exception e) { logger.error("写入错误excel错误", e); throw new RuntimeException(e); } finally { excelTplVO.setTableLabel(tableLabel); excelTplVO.setFile(outputStream.toByteArray()); IoUtil.close(outputStream); } return excelTplVO; } private String sanitizeSheetName(String sheetName) { if (sheetName == null) { return null; } // 替换特殊字符为 "_" return sheetName.replaceAll("[/\\\\*?\\[\\]]", "_");请帮我分析一下 如果要在导出Excel文件时添加批注应该怎么写
05-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值