Archived
switch to poi-tl for template rendering, add OpenAPI spec
- Replace manual DOCX ZIP manipulation with poi-tl library
- Templates use {{variable}} syntax, editable in Word
- Add postProcess hook for dynamic content (table rows)
- Clean up unused generate() method from TemplateProvider
- Remove custom ExportResult/ExportFileWriter complexity
- Add docs/openapi.yaml — OpenAPI 3.1 spec for export API
This commit is contained in:
@@ -2,11 +2,11 @@ package com.gmp.mock.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.deepoove.poi.XWPFTemplate;
|
||||
import com.deepoove.poi.xwpf.NiceXWPFDocument;
|
||||
import com.gmp.mock.template.TemplateProvider;
|
||||
import com.gmp.mock.template.TemplateRegistry;
|
||||
|
||||
@@ -19,23 +19,29 @@ public class DocxService {
|
||||
this.templateRegistry = templateRegistry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ExportResult containing file name and a writer that writes directly to an OutputStream
|
||||
* @throws TemplateNotFoundException if templateId is not registered
|
||||
*/
|
||||
public ExportResult export(String exportId) {
|
||||
TemplateProvider provider = templateRegistry.get(exportId);
|
||||
if (provider == null) {
|
||||
throw new TemplateNotFoundException(exportId);
|
||||
}
|
||||
|
||||
// Return a writer callback instead of buffering everything in memory.
|
||||
// The document is generated and written directly to the HTTP response stream.
|
||||
ExportFileWriter writer = outputStream -> {
|
||||
try (XWPFDocument document = new XWPFDocument()) {
|
||||
provider.generate(document);
|
||||
document.write(outputStream);
|
||||
outputStream.flush();
|
||||
try {
|
||||
// 1. poi-tl: compile template and render text placeholders
|
||||
XWPFTemplate template = XWPFTemplate.compile(provider.getTemplateResource());
|
||||
template.render(provider.getDataModel());
|
||||
|
||||
// 2. Get the underlying document for post-processing
|
||||
NiceXWPFDocument doc = template.getXWPFDocument();
|
||||
|
||||
// 3. Post-process (e.g. add table rows)
|
||||
provider.postProcess(doc);
|
||||
|
||||
// 4. Write to output stream
|
||||
template.write(outputStream);
|
||||
template.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("生成文档失败", e);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.gmp.mock.template;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
|
||||
@@ -10,5 +12,30 @@ public interface TemplateProvider {
|
||||
|
||||
String getFileName();
|
||||
|
||||
void generate(XWPFDocument document) throws IOException;
|
||||
/**
|
||||
* @return InputStream pointing to the .docx template file
|
||||
*/
|
||||
InputStream getTemplateResource();
|
||||
|
||||
/**
|
||||
* @return data model for poi-tl template rendering
|
||||
*/
|
||||
Map<String, Object> getDataModel();
|
||||
|
||||
/**
|
||||
* Post-processing hook called after poi-tl rendering.
|
||||
* Override to add dynamic content (e.g. table rows) that can't
|
||||
* be expressed with simple {{variable}} placeholders.
|
||||
*/
|
||||
default void postProcess(XWPFDocument document) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/**
|
||||
* Old generate method — no longer needed when using poi-tl.
|
||||
* Kept for backward compatibility; can be removed once all templates migrate.
|
||||
*/
|
||||
default void generate(XWPFDocument document) throws IOException {
|
||||
throw new UnsupportedOperationException("Use poi-tl template instead");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
package com.gmp.mock.template.annualReport;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTable;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.deepoove.poi.XWPFTemplate;
|
||||
import com.gmp.mock.template.TemplateProvider;
|
||||
|
||||
/**
|
||||
* poi-tl based template provider.
|
||||
*
|
||||
* Simple text placeholders ({{title}}, {{companyName}}, etc.) are handled
|
||||
* by poi-tl directly. Table rows are built programmatically with POI API
|
||||
* after poi-tl rendering, because poi-tl's table loop syntax can be
|
||||
* finicky with raw XML templates.
|
||||
*
|
||||
* To edit the template: open the .docx in Word, write {{placeholders}}.
|
||||
*/
|
||||
@Component
|
||||
public class AnnualReportProvider implements TemplateProvider {
|
||||
|
||||
private static final Map<String, String> DEFAULT_VARS = Map.ofEntries(
|
||||
Map.entry("title", "2025 年度工作报告"),
|
||||
Map.entry("companyName", "示例科技有限公司"),
|
||||
Map.entry("reportPeriod", "2025年1月 - 2025年12月"),
|
||||
Map.entry("metric1Name", "营业收入"),
|
||||
Map.entry("metric1Value", "¥ 1,234,567"),
|
||||
Map.entry("metric1Change","+15.3%"),
|
||||
Map.entry("metric2Name", "净利润"),
|
||||
Map.entry("metric2Value", "¥ 321,098"),
|
||||
Map.entry("metric2Change","+8.7%"),
|
||||
Map.entry("generatedDate",
|
||||
LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")))
|
||||
private static final List<Map<String, String>> METRICS = List.of(
|
||||
Map.of("name", "营业收入", "value", "¥ 1,234,567", "change", "+15.3%"),
|
||||
Map.of("name", "净利润", "value", "¥ 321,098", "change", "+8.7%"),
|
||||
Map.of("name", "毛利率", "value", "45.2%", "change", "+2.1%")
|
||||
);
|
||||
|
||||
@Override
|
||||
@@ -45,56 +45,37 @@ public class AnnualReportProvider implements TemplateProvider {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void generate(XWPFDocument document) throws IOException {
|
||||
ClassPathResource resource = new ClassPathResource("templates/annualReportTemplate.docx");
|
||||
if (!resource.exists()) {
|
||||
throw new IOException("模板文件未找到: templates/annualReportTemplate.docx");
|
||||
}
|
||||
|
||||
byte[] templateBytes;
|
||||
try (InputStream is = resource.getInputStream()) {
|
||||
templateBytes = is.readAllBytes();
|
||||
}
|
||||
|
||||
// Replace ${placeholders} in word/document.xml inside the ZIP
|
||||
byte[] modified = replacePlaceholdersInDocx(templateBytes);
|
||||
|
||||
// Read the modified docx and copy content into the output document
|
||||
try (InputStream modifiedIs = new ByteArrayInputStream(modified);
|
||||
XWPFDocument templateDoc = new XWPFDocument(modifiedIs)) {
|
||||
|
||||
for (var para : templateDoc.getParagraphs()) {
|
||||
var newPara = document.createParagraph();
|
||||
newPara.getCTP().set(para.getCTP().copy());
|
||||
}
|
||||
for (var table : templateDoc.getTables()) {
|
||||
var newTable = document.createTable();
|
||||
newTable.getCTTbl().set(table.getCTTbl().copy());
|
||||
public InputStream getTemplateResource() {
|
||||
try {
|
||||
ClassPathResource resource = new ClassPathResource("templates/annualReportTemplate.docx");
|
||||
if (!resource.exists()) {
|
||||
throw new RuntimeException("模板文件未找到: templates/annualReportTemplate.docx");
|
||||
}
|
||||
return resource.getInputStream();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] replacePlaceholdersInDocx(byte[] docxBytes) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(docxBytes));
|
||||
ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
@Override
|
||||
public Map<String, Object> getDataModel() {
|
||||
return Map.of(
|
||||
"title", "2025 年度工作报告",
|
||||
"companyName", "示例科技有限公司",
|
||||
"reportPeriod", "2025年1月 - 2025年12月",
|
||||
"generatedDate", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))
|
||||
);
|
||||
}
|
||||
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
zos.putNextEntry(new ZipEntry(entry.getName()));
|
||||
|
||||
byte[] content = zis.readAllBytes();
|
||||
if ("word/document.xml".equals(entry.getName())) {
|
||||
String xml = new String(content, "UTF-8");
|
||||
for (Map.Entry<String, String> var : DEFAULT_VARS.entrySet()) {
|
||||
xml = xml.replace("${" + var.getKey() + "}", var.getValue());
|
||||
}
|
||||
content = xml.getBytes("UTF-8");
|
||||
}
|
||||
zos.write(content);
|
||||
zos.closeEntry();
|
||||
}
|
||||
@Override
|
||||
public void postProcess(XWPFDocument document) {
|
||||
// Add data rows to the first table in the document
|
||||
XWPFTable table = document.getTables().get(0);
|
||||
for (Map<String, String> metric : METRICS) {
|
||||
XWPFTableRow row = table.createRow();
|
||||
row.getCell(0).setText(metric.get("name"));
|
||||
row.getCell(1).setText(metric.get("value"));
|
||||
row.getCell(2).setText(metric.get("change"));
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user