「神器來襲!」Java 一鍵搞定 Markdown 轉(zhuǎn) Word,標(biāo)題/段落/表格/Echarts 圖全支持!
在日常開發(fā)和文檔生成工作中,我們經(jīng)常遇到這樣的需求: 團隊協(xié)作時編寫文檔喜歡用 Markdown,輕便、直觀、好管理;但是對外展示時,領(lǐng)導(dǎo)和客戶往往需要 Word 文檔。市面上的工具大多支持有限,尤其是表格和圖表部分兼容性差、樣式丟失嚴(yán)重。
于是我們開發(fā)了一個輕量級 Java 工具 —— md2doc-plus。它不僅能解析常見 Markdown 元素,還能將 ECharts 圖表直接轉(zhuǎn)換為 Word 內(nèi)嵌圖表,并支持動態(tài)模板,真正做到“一鍵轉(zhuǎn) Word”,極大提升了效率。
項目結(jié)構(gòu)與實現(xiàn)思路
md2doc-plus 基于 Java 17 和 Apache POI 構(gòu)建,采用模塊化設(shè)計,主要目錄組織如下:
src/
└── main/
├── java/com/icoderoad/md2docplus/
│ ├── parser/ # Markdown解析模塊
│ ├── generator/ # Word文檔生成模塊
│ ├── converter/ # 圖表轉(zhuǎn)換器
│ ├── template/ # 模板引擎
│ └── model/ # 參數(shù)與數(shù)據(jù)模型
└── resources/
└── templates/ # Word模板文件核心模塊:
Markdown 解析器:識別標(biāo)題、段落、表格、ECharts 配置等。
文檔生成器:基于 Apache POI 操作文檔。
模板引擎:生成包含占位符的 Word 模板,支持動態(tài)內(nèi)容填充。
圖表轉(zhuǎn)換器:將 ECharts JSON 配置渲染為 Word 圖表對象。
核心功能亮點
完整 Markdown 支持
- 標(biāo)題(H1-H6)
- 段落文本
- 表格
- ECharts 圖表
ECharts 圖表解析
可直接識別 Markdown 中的 ECharts 配置并生成 Word 圖表,例如:
{
title: { text: "月度銷售數(shù)據(jù)" },
xAxis: { type: "category", data: ["1月", "2月", "3月", "4月", "5月", "6月"] },
yAxis: { type: "value", name: "銷售額" },
series: [{
name: "銷售額",
type: "line",
data: [15.32, 15.87, 14.96, 16.23, 13.21, 13.53]
}]
}動態(tài)模板
解析時會為表格、圖表生成占位符,方便后續(xù)填充。
高度可定制
通過 WordParams 和 ChartTable 等模型,用戶可定制格式。
易集成
只需依賴 jar 包,即可集成進任何 Java 應(yīng)用。
核心代碼實現(xiàn)
以下展示部分關(guān)鍵實現(xiàn):
Markdown 解析與文檔結(jié)構(gòu)創(chuàng)建
package com.icoderoad.md2docplus.generator;
public class DynamicWordDocumentCreator {
/**
* 解析Markdown并生成Word結(jié)構(gòu)
*/
private static void parseAndCreateDocumentStructure(XWPFDocument document, String markdownContent) {
Pattern headerPattern = Pattern.compile("^(#{1,6})\\s+(.*)$", Pattern.MULTILINE);
String[] lines = markdownContent.split("\n");
int chartIndex = 1, tableIndex = 1;
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// 標(biāo)題解析
Matcher headerMatcher = headerPattern.matcher(line);
if (headerMatcher.find()) {
int level = headerMatcher.group(1).length();
String title = headerMatcher.group(2);
XWPFParagraph headerParagraph = document.createParagraph();
XWPFRun run = headerParagraph.createRun();
run.setText(title);
run.setBold(true);
run.setFontFamily("宋體");
run.setFontSize(22 - (level * 2));
continue;
}
// 普通段落
if (!line.trim().isEmpty()) {
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(line);
run.setFontFamily("宋體");
run.setFontSize(12);
}
}
}
}ECharts 轉(zhuǎn)換器
package com.icoderoad.md2docplus.converter;
public class EChartsToWordConverter {
public static void convertEChartsToWordChart(WordParams params, String chartKey, String echartsConfig) throws IOException {
JsonNode rootNode = new ObjectMapper().readTree(echartsConfig);
String title = rootNode.path("title").path("text").asText("默認(rèn)標(biāo)題");
ChartTable chartTable = params.addChart(chartKey).setTitle(title);
// 處理X軸
JsonNode xAxisData = rootNode.path("xAxis").path("data");
for (JsonNode node : xAxisData) {
chartTable.getXAxis().addData(node.asText());
}
}
}Markdown 表格解析
package com.icoderoad.md2docplus.parser;
public class MarkdownTableParser {
public static List<List<String>> parseTable(String markdownTable) {
List<List<String>> tableData = new ArrayList<>();
String[] lines = markdownTable.split("\n");
for (String line : lines) {
if (line.matches("^\\|?\\s*[-|:\\s]+\\|?\\s*$")) continue;
String[] cells = line.split("\\|");
List<String> row = Arrays.stream(cells)
.map(String::trim)
.filter(c -> !c.isEmpty())
.collect(Collectors.toList());
if (!row.isEmpty()) tableData.add(row);
}
return tableData;
}
}使用示例
package com.icoderoad.md2docplus;
public class Test {
public static void main(String[] args) throws Exception {
MarkdownToWordConverter.convertMarkdownFileToWord(
"./markdown/example.md",
"./word/output.docx"
);
}
}完整 pom.xml 配置
下面提供一個可直接構(gòu)建運行的 Maven 配置:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.icoderoad</groupId>
<artifactId>md2doc-plus</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- Apache POI Word 處理 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!-- JSON 解析 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<!-- Commons IO 工具類 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.9</version>
</dependency>
<!-- JUnit 測試 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Compiler 插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<!-- 打包插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.icoderoad.md2docplus.Test</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals><goal>single</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>存在的問題與改進方向
- Word 標(biāo)題樣式缺失,目錄需要手動生成。
- 圖表在 Word 內(nèi)渲染效果有限,部分樣式需手動調(diào)整。
- 未來計劃支持更多 Markdown 擴展語法,如代碼高亮、圖片解析。
結(jié)語
從 Markdown 到 Word 的轉(zhuǎn)換,看似簡單,其實要兼顧語法解析、文檔格式、圖表渲染等多個環(huán)節(jié)。md2doc-plus 在輕量化和可擴展性上做了平衡,既能滿足日常報告生成需求,又便于集成到其他系統(tǒng)中。
如果你也在尋找一款能處理 標(biāo)題 / 段落 / 表格 / ECharts 圖表 的 Markdown 轉(zhuǎn) Word 工具,那么不妨試試 md2doc-plus —— 讓你的文檔轉(zhuǎn)換過程真正做到 一鍵完成 。





























