diff --git a/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/controller/admin/costfee/CostFeeController.java b/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/controller/admin/costfee/CostFeeController.java index fee8c95..c26a364 100644 --- a/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/controller/admin/costfee/CostFeeController.java +++ b/urbanops-module-garden/src/main/java/com/zteits/urbanops/module/garden/controller/admin/costfee/CostFeeController.java @@ -5,16 +5,25 @@ import com.zteits.urbanops.framework.excel.core.util.ExcelUtils; import com.zteits.urbanops.module.garden.controller.admin.costfee.vo.WaterFeeImport; import com.zteits.urbanops.module.garden.enums.TemplateEnum; import com.zteits.urbanops.module.garden.service.costfee.CostFeeService; +import com.zteits.urbanops.module.system.api.dept.DeptApi; +import com.zteits.urbanops.module.system.api.dept.dto.DeptRespDTO; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.annotation.security.PermitAll; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.xssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -25,6 +34,7 @@ import java.lang.reflect.Method; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.stream.Collectors; import static com.zteits.urbanops.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST; import static com.zteits.urbanops.framework.common.pojo.CommonResult.success; @@ -49,6 +59,12 @@ public class CostFeeController{ @Value("${static.resource.server.enable}") private Boolean staticResourceServerenable; + @Autowired + private ResourceLoader resourceLoader; + + @jakarta.annotation.Resource + private DeptApi deptApi; + // Excel文件校验相关 private static final List ALLOWED_EXCEL_SUFFIX = Arrays.asList(".xlsx", ".xlsm"); private static final String EXCEL_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; @@ -59,6 +75,7 @@ public class CostFeeController{ */ @GetMapping("/get-import-template") @Operation(summary = "获得导入用户模板") + @PermitAll public void importTemplate(HttpServletResponse response, @RequestParam("templateName") String templateName) throws IOException { // 参数校验 @@ -74,29 +91,143 @@ public class CostFeeController{ return; } - if (staticResourceServerenable) { - // 构建完整的静态服务器URL(确保路径正确) - String serverUrl = staticResourceServerUrl; - if (serverUrl != null && !serverUrl.endsWith("/")) { - serverUrl += "/"; // 确保URL以/结尾,避免拼接错误 - } + writeAndModifyTemplate(response, template.getName(), template.getStartIndex()); + } + + private void writeAndModifyTemplate(HttpServletResponse response, + String downloadFileName, + int startIndexRow) throws IOException { + + // 拼接模板路径 + String serverUrl = staticResourceServerUrl; + if (serverUrl != null && !serverUrl.endsWith("/")) { + serverUrl += "/"; + } + String fullPath = serverUrl + downloadFileName; + fullPath = fullPath.replace("\\", "/"); + + Resource resource = resourceLoader.getResource(fullPath); + + // 检查文件是否存在 + if (!resource.exists()) { + response.sendError(HttpServletResponse.SC_NOT_FOUND, "模板文件不存在"); + return; + } + + // 设置下载响应头 + response.reset(); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("UTF-8"); + String encodedName = URLEncoder.encode(downloadFileName, "UTF-8"); + response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodedName); + + try (InputStream in = resource.getInputStream(); + XSSFWorkbook workbook = new XSSFWorkbook(in); + OutputStream out = response.getOutputStream()) { - String encodedFileName = URLEncoder.encode(template.getName().split("\\.")[0], StandardCharsets.UTF_8.name()); + XSSFSheet sheet = workbook.getSheetAt(0); - String templateFileName = encodedFileName + "." + template.getName().split("\\.")[1]; + // ============================================== + // 获取最新单位列表 + // ============================================== + List companyList = deptApi.getSubDeptList(); + List newUnits = companyList.stream() + .map(DeptRespDTO::getName) + .filter(Objects::nonNull) + .toList(); - String templateUrl = serverUrl + templateFileName; // 包含templates目录 + log.info("加载到单位列表:{},共{}条", newUnits, newUnits.size()); - // 方式1:重定向到静态资源服务器 - response.sendRedirect(templateUrl); - } else { - String templateFileName = templateName + "." + template.getName().split("\\.")[1]; + // ============================================== + // 生成新下拉 + 自动赋值 + // ============================================== + createDropdownAndSetValue(sheet, newUnits, startIndexRow); - // 写入模板文件到响应 - writeTemplateToResponse(response, template.getName(), templateFileName); + // 写入并强制刷新 + workbook.write(out); + out.flush(); + + } catch (Exception e) { + log.error("模板处理失败", e); + throw new IOException("文件处理失败", e); } } + /** + * 创建下拉框 + 给单元格赋值 + */ + private void createDropdownAndSetValue(XSSFSheet sheet, List options, int startRow) { + if (options.isEmpty()) { + log.error("下拉选项为空,不创建"); + return; + } + + // 获取表头行 + Row headerRow = sheet.getRow(startRow - 1); + if (headerRow == null) { + log.error("表头行不存在:{}", startRow - 1); + return; + } + + // 查找“所属单位”列 + int targetCol = -1; + for (Cell cell : headerRow) { + if (cell != null && cell.getCellType() == CellType.STRING) { + String val = cell.getStringCellValue().trim(); + if (val.contains("所属单位") || val.contains("所属公司") ) { + targetCol = cell.getColumnIndex(); + break; + } + } + } + + if (targetCol == -1) { + log.error("未找到【所属单位】列表头"); + return; + } + + // 取消列隐藏 + sheet.setColumnHidden(targetCol, false); + + // ============================================== + // 遍历行:清空原有内容 + 设置默认值 + // ============================================== + int endRow = 100; + for (int r = startRow; r <= endRow; r++) { + Row row = sheet.getRow(r); + if (row == null) { + row = sheet.createRow(r); + } + + Cell cell = row.getCell(targetCol); + if (cell == null) { + cell = row.createCell(targetCol); + } + String unit = cell.getStringCellValue(); + // 默认赋值【第一个单位】,你可以根据业务改成其他值 + if (!StringUtils.isEmpty(unit)) { + cell.setCellValue(options.get(2)); + } + } + + // ============================================== + // 创建下拉框(作用范围:startRow ~ 1000行) + // ============================================== + CellRangeAddressList regions = new CellRangeAddressList(startRow, endRow, targetCol, targetCol); + XSSFDataValidationHelper helper = new XSSFDataValidationHelper(sheet); + XSSFDataValidationConstraint constraint = (XSSFDataValidationConstraint) helper.createExplicitListConstraint( + options.toArray(new String[0]) + ); + XSSFDataValidation validation = (XSSFDataValidation) helper.createValidation(constraint, regions); + + // 下拉框基础配置 + validation.setEmptyCellAllowed(true); + validation.setSuppressDropDownArrow(true); + sheet.addValidationData(validation); + + log.info("【成功】为列{}添加下拉并赋值,行{}~{},选项数:{}", + targetCol, startRow, endRow, options.size()); + } /** * Excel文件上传预览 @@ -214,31 +345,6 @@ public class CostFeeController{ } /** - * 写入模板文件到响应流 - */ - private void writeTemplateToResponse(HttpServletResponse response, String filename, String templatePath) throws IOException { - // 设置响应头 - response.setContentType(EXCEL_MIME_TYPE); - response.setCharacterEncoding("UTF-8"); - String encodedFileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20"); - response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName); - response.setHeader("Cache-Control", "no-store"); // 禁止缓存 - - // 读取模板文件并写入响应 - try (InputStream in = new ClassPathResource("template/" + templatePath).getInputStream(); - OutputStream out = response.getOutputStream()) { - - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = in.read(buffer)) != -1) { - out.write(buffer, 0, bytesRead); - } - out.flush(); - } - } - - - /** * 校验Excel文件有效性(后缀+MIME类型) */ private boolean isValidExcelFile(MultipartFile file) {