首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 將文字內容儲存為 Word (.docx) 檔案:Apache POI 完整實作教學

     編輯:程式設計綜合問答

方案選擇

Android 無內建 Word 產生 API,業界標準做法是使用 Apache POI(支援 .docx / .xlsx / .pptx)。

Gradle 依賴設定

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;
}

注意事項

  • POI 體積較大(~10 MB),APK 會膨脹;若只需簡單報表,可考慮 HTML 轉 Word 或伺服端產生。
  • Android 10+ 需使用 MediaStore 或 FileProvider 分享檔案。
  • 中文字型需嵌入或指定系統字型,否則可能顯示方塊字。

替代方案速查

方案優點缺點
POI功能完整、純離線體積大、記憶體佔用高
docx4jJAXB 架構、支援複雜樣式依賴更多、啟動慢
伺服端產生 + 下載App 輕量、格式精確需網路、後端成本
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved