Android 無內建 Word 產生 API,業界標準做法是使用 Apache POI(支援 .docx / .xlsx / .pptx)。
dependencies {
implementation 'org.apache.poi:poi:5.3.0'
implementation 'org.apache.poi:poi-ooxml:5.3.0'
// Android 需額外排除重複類別
implementation 'org.apache.xmlbeans:xmlbeans:5.1.1'
}
public File createDocx(Context ctx, String title, String content) throws IOException {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
p.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = p.createRun();
run.setText(title);
run.setBold(true);
run.setFontSize(18);
p = doc.createParagraph();
run = p.createRun();
run.setText(content);
run.setFontSize(12);
File file = new File(ctx.getExternalFilesDir(null), "export.docx");
try (FileOutputStream fos = new FileOutputStream(file)) {
doc.write(fos);
}
doc.close();
return file;
}
MediaStore 或 FileProvider 分享檔案。| 方案 | 優點 | 缺點 |
|---|---|---|
| POI | 功能完整、純離線 | 體積大、記憶體佔用高 |
| docx4j | JAXB 架構、支援複雜樣式 | 依賴更多、啟動慢 |
| 伺服端產生 + 下載 | App 輕量、格式精確 | 需網路、後端成本 |