元数据模板导出 excel导入

This commit is contained in:
2026-10-23 18:45:12 +08:00
parent 8b6f00b117
commit ddc0864f06
8 changed files with 805 additions and 4 deletions
+7
View File
@@ -89,6 +89,13 @@
<version>${hutool.version}</version>
</dependency>
<!-- Excel 导入导出 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
@@ -2,14 +2,22 @@ package com.banben.modules.resource.controller;
import com.banben.common.PageResult;
import com.banben.common.Result;
import com.banben.modules.resource.dto.ImportResult;
import com.banben.modules.resource.dto.VersionResourceQuery;
import com.banben.modules.resource.entity.VersionResource;
import com.banben.modules.resource.service.VersionResourceExcelService;
import com.banben.modules.resource.service.VersionResourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* 版本资源元数据管理接口。
@@ -48,6 +56,24 @@ import org.springframework.web.bind.annotation.*;
public class VersionResourceController {
private final VersionResourceService versionResourceService;
private final VersionResourceExcelService excelService;
@Operation(summary = "下载 Excel 导入模板")
@GetMapping("/template")
public void downloadTemplate(HttpServletResponse response) throws IOException {
String fileName = URLEncoder.encode("版本资源导入模板.xlsx", StandardCharsets.UTF_8);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition",
"attachment; filename=" + fileName + "; filename*=UTF-8''" + fileName);
excelService.writeTemplate(response.getOutputStream());
}
@Operation(summary = "Excel 导入版本资源")
@PostMapping("/import")
public Result<ImportResult> importExcel(@RequestParam("file") MultipartFile file) throws IOException {
return Result.success(excelService.importExcel(file));
}
@Operation(summary = "分页查询版本资源")
@GetMapping("/page")
@@ -0,0 +1,38 @@
package com.banben.modules.resource.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Excel 导入结果。
*
* <p>导入不会因为个别行出错而整体失败:能入库的照常入库,
* 失败的行记录行号与原因,前端一次性提示给用户。</p>
*/
@Data
public class ImportResult {
/** 解析到的有效数据行数 */
private int total;
/** 新增成功条数 */
private int inserted;
/** 按加工编号匹配到已有记录并更新的条数 */
private int updated;
/** 失败条数 */
private int failed;
/** 失败明细,格式如「第 5 行:正题名不能为空」 */
private List<String> errors = new ArrayList<>();
public void addError(int excelRowNum, String reason) {
if (errors.size() < 50) {
errors.add("第 " + excelRowNum + " 行:" + reason);
}
failed++;
}
}
@@ -0,0 +1,365 @@
package com.banben.modules.resource.service;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.banben.modules.resource.dto.ImportResult;
import com.banben.modules.resource.entity.VersionResource;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
/**
* 版本资源 Excel 模板导出与导入。
*
* <p>模板结构:第 1 行表头(* 表示必填),第 2 行填写说明,第 3 行起为用户数据。
* 导入时按表头名称匹配列,因此用户调整列顺序也不影响。</p>
*/
@Service
@RequiredArgsConstructor
public class VersionResourceExcelService {
private final VersionResourceService versionResourceService;
/** 单次导入的最大数据行数,防止超大文件拖垮服务 */
private static final int MAX_ROWS = 5000;
private record Column(String header, String field,
BiConsumer<VersionResource, String> setter, int maxLen, String hint) {
}
private static final List<Column> COLUMNS = List.of(
new Column("正题名*", "title", VersionResource::setTitle, 512, "必填"),
new Column("加工编号", "processNo", VersionResource::setProcessNo, 128, "选填;系统中已存在则更新该条"),
new Column("责任者", "author", VersionResource::setAuthor, 512, "选填;多人用 ; 分隔"),
new Column("责任方式", "responsibility", VersionResource::setResponsibility, 256, "选填;如 著、编、译"),
new Column("中图分类", "clcCode", VersionResource::setClcCode, 64, "选填;如 G250.7"),
new Column("主题词", "keywords", VersionResource::setKeywords, 512, "选填;多个用 ; 分隔"),
new Column("摘要", "summary", VersionResource::setSummary, 2000, "选填;建议不少于 100 字"),
new Column("出版年份", "publishYear", VersionResource::setPublishYear, 8, "选填;格式 yyyy"),
new Column("出版者", "publisher", VersionResource::setPublisher, 256, "选填"),
new Column("出版地", "publishPlace", VersionResource::setPublishPlace, 128, "选填"),
new Column("出版日期", "publishDate", VersionResource::setPublishDate, 32, "选填;如 2026-01-01"),
new Column("版本版次", "edition", VersionResource::setEdition, 128, "选填"),
new Column("ISBN", "isbn", VersionResource::setIsbn, 64, "选填"),
new Column("内容形式", "contentForm", VersionResource::setContentForm, 64, "选填;如 文本"),
new Column("媒体类型", "mediaType", VersionResource::setMediaType, 32, "选填;纸质 或 电子"),
new Column("格式", "format", VersionResource::setFormat, 64, "选填;如 PDF"),
new Column("页码", "pageCount", VersionResource::setPageCount, 64, "选填"),
new Column("语种", "language", VersionResource::setLanguage, 16, "选填;三位代码,如 chi"),
new Column("来源馆", "sourceLibrary", VersionResource::setSourceLibrary, 256, "选填"),
new Column("数据提交单位", "submitOrg", VersionResource::setSubmitOrg, 256, "选填"),
new Column("任务年份", "taskYear", VersionResource::setTaskYear, 8, "选填;格式 yyyy"),
new Column("全文地址", "fulltextUrl", VersionResource::setFulltextUrl, 1024, "选填"),
new Column("是否特藏", "isSpecial", (r, v) -> { }, 4, "选填;是 或 否")
);
// ==================== 模板导出 ====================
public void writeTemplate(OutputStream out) throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("版本资源");
CellStyle headStyle = buildHeadStyle(wb);
CellStyle hintStyle = buildHintStyle(wb);
Row head = sheet.createRow(0);
Row hint = sheet.createRow(1);
head.setHeightInPoints(24);
hint.setHeightInPoints(18);
for (int i = 0; i < COLUMNS.size(); i++) {
Column col = COLUMNS.get(i);
Cell h = head.createCell(i);
h.setCellValue(col.header());
h.setCellStyle(headStyle);
Cell t = hint.createCell(i);
t.setCellValue(col.hint());
t.setCellStyle(hintStyle);
int width = Math.max(12, Math.min(46, displayWidth(col.header()) + 4));
if ("summary".equals(col.field()) || "fulltextUrl".equals(col.field())) {
width = 46;
}
sheet.setColumnWidth(i, width * 256);
}
sheet.createFreezePane(0, 2);
// 媒体类型、是否特藏加下拉,避免填错
addDropdown(sheet, indexOf("mediaType"), new String[]{"纸质", "电子"});
addDropdown(sheet, indexOf("isSpecial"), new String[]{"是", "否"});
wb.write(out);
}
}
private CellStyle buildHeadStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setBold(true);
font.setFontHeightInPoints((short) 11);
font.setColor(IndexedColors.WHITE.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
border(style);
return style;
}
private CellStyle buildHintStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontHeightInPoints((short) 9);
font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFont(font);
style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setWrapText(true);
border(style);
return style;
}
private void border(CellStyle style) {
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
}
private int displayWidth(String text) {
int w = 0;
for (char c : text.toCharArray()) {
w += c > 127 ? 2 : 1;
}
return w;
}
private int indexOf(String field) {
for (int i = 0; i < COLUMNS.size(); i++) {
if (COLUMNS.get(i).field().equals(field)) return i;
}
return -1;
}
private void addDropdown(Sheet sheet, int colIndex, String[] options) {
if (colIndex < 0) return;
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint =
helper.createExplicitListConstraint(options);
CellRangeAddressList range = new CellRangeAddressList(2, MAX_ROWS, colIndex, colIndex);
DataValidation validation = helper.createValidation(constraint, range);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
// ==================== 导入 ====================
public ImportResult importExcel(MultipartFile file) throws IOException {
ImportResult result = new ImportResult();
if (file == null || file.isEmpty()) {
result.addError(0, "请选择要导入的 Excel 文件");
return result;
}
try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
Sheet sheet = wb.getSheetAt(0);
if (sheet == null || sheet.getLastRowNum() < 1) {
result.addError(0, "表格为空,请使用系统导出的模板填写数据");
return result;
}
// 1) 表头 → 列号
Row headRow = sheet.getRow(0);
Map<String, Integer> colIndex = new HashMap<>();
for (Cell cell : headRow) {
String name = normalizeHeader(cellText(cell));
if (StrUtil.isNotBlank(name)) {
colIndex.put(name, cell.getColumnIndex());
}
}
if (!colIndex.containsKey("正题名")) {
result.addError(1, "表头缺少「正题名」列,请使用系统导出的模板");
return result;
}
// 2) 判断第 2 行是否为说明行
int startRow = 1;
Row second = sheet.getRow(1);
if (second != null) {
String first = cellText(second.getCell(0));
if (first != null && (first.startsWith("必填") || first.startsWith("选填"))) {
startRow = 2;
}
}
// 3) 逐行解析
List<VersionResource> parsed = new ArrayList<>();
List<Integer> rowNums = new ArrayList<>();
int last = Math.min(sheet.getLastRowNum(), startRow + MAX_ROWS);
for (int r = startRow; r <= last; r++) {
Row row = sheet.getRow(r);
if (row == null) continue;
VersionResource res = new VersionResource();
boolean empty = true;
for (Column col : COLUMNS) {
Integer idx = colIndex.get(normalizeHeader(col.header()));
if (idx == null) continue;
String value = cellText(row.getCell(idx));
if (StrUtil.isBlank(value)) continue;
empty = false;
if ("isSpecial".equals(col.field())) {
res.setIsSpecial(parseBool(value) ? 1 : 0);
} else {
col.setter().accept(res, truncate(value.trim(), col.maxLen()));
}
}
if (empty) continue;
int excelRowNum = r + 1;
if (StrUtil.isBlank(res.getTitle())) {
result.addError(excelRowNum, "正题名不能为空");
continue;
}
if (StrUtil.isBlank(res.getGovernStatus())) {
res.setGovernStatus("RAW");
}
if (res.getDeleted() == null) {
res.setDeleted(0);
}
if (res.getIsSpecial() == null) {
res.setIsSpecial(0);
}
parsed.add(res);
rowNums.add(excelRowNum);
}
result.setTotal(parsed.size());
if (parsed.isEmpty()) {
if (result.getFailed() == 0) {
result.addError(0, "未读取到有效数据行,请从第 3 行开始填写");
}
return result;
}
// 4) 按加工编号匹配已有记录
Map<String, Long> existing = findExisting(parsed);
List<VersionResource> inserts = new ArrayList<>();
List<VersionResource> updates = new ArrayList<>();
for (int i = 0; i < parsed.size(); i++) {
VersionResource res = parsed.get(i);
Long existId = StrUtil.isBlank(res.getProcessNo())
? null : existing.get(res.getProcessNo().trim());
if (existId != null) {
res.setId(existId);
updates.add(res);
} else {
inserts.add(res);
}
}
// 5) 分批写库
if (!inserts.isEmpty()) {
versionResourceService.saveBatch(inserts, 500);
}
if (!updates.isEmpty()) {
versionResourceService.updateBatchById(updates, 500);
}
result.setInserted(inserts.size());
result.setUpdated(updates.size());
return result;
} catch (Exception e) {
result.addError(0, "文件解析失败:" + e.getMessage());
return result;
}
}
/** 一次性查出所有已存在的加工编号,避免逐行查库 */
private Map<String, Long> findExisting(List<VersionResource> list) {
List<String> nos = list.stream()
.map(VersionResource::getProcessNo)
.filter(StrUtil::isNotBlank)
.map(String::trim)
.distinct()
.collect(Collectors.toList());
if (nos.isEmpty()) return Collections.emptyMap();
LambdaQueryWrapper<VersionResource> wrapper = new LambdaQueryWrapper<>();
wrapper.in(VersionResource::getProcessNo, nos);
return versionResourceService.list(wrapper).stream()
.filter(r -> StrUtil.isNotBlank(r.getProcessNo()))
.collect(Collectors.toMap(
r -> r.getProcessNo().trim(),
VersionResource::getId,
(a, b) -> a));
}
private String normalizeHeader(String s) {
if (s == null) return "";
return s.replace("*", "")
.replace("*", "")
.replace(" ", "")
.replace(" ", "")
.trim();
}
private String cellText(Cell cell) {
if (cell == null) return null;
CellType type = cell.getCellType();
if (type == CellType.FORMULA) {
type = cell.getCachedFormulaResultType();
}
switch (type) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getLocalDateTimeCellValue().toLocalDate().toString();
}
double d = cell.getNumericCellValue();
if (d == Math.floor(d) && !Double.isInfinite(d)) {
return String.valueOf((long) d);
}
return String.valueOf(d);
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
default:
return null;
}
}
private boolean parseBool(String v) {
String s = v.trim();
return "是".equals(s) || "1".equals(s) || "true".equalsIgnoreCase(s) || "y".equalsIgnoreCase(s);
}
private String truncate(String v, int max) {
if (v == null) return null;
return v.length() > max ? v.substring(0, max) : v;
}
}