補充說明: 以 NuGet 安裝 ClosedXML. ClosedXML 是為 Office Open XML 提供容易操作的程式介面,程式介面簡潔易用。 ClosedXML 是 OpenSource, 可在 GitHub 上取得原始碼: https://github.com/ClosedXML/ClosedXML 文件說明為: https://docs.closedxml.io/en/latest/ Office Open XML(縮寫:Open XML、OpenXML或OOXML),為由 Microsoft 開發的一種以 XML 為基礎, 並以 ZIP 格式壓縮的電子檔案規範, 支援 Office Word、Excel、備忘錄、PowerPoint等檔案格式。 https://zh.wikipedia.org/zh-tw/Office_Open_XML 提問: 給我 C# .Net 8.0 的 Class, 包含ImportJson(), ExportJson()函數, 可將 Word 檔案(.docx), 匯入或匯出為 Json UTF8 文字檔案. 以下是 C# .NET 8.0 的範例程式碼,包含 `ImportJson()` 和 `ExportJson()` 函數,用於將 Word 文件(.docx 格式)與 JSON UTF-8 文字檔案相互轉換。此程式使用 `OpenXml` SDK 和 `System.Text.Json` 來處理 Word 和 JSON。 ### **完整程式碼** ```csharp using System; using System.Collections.Generic; using System.IO; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using System.Text.Json; public class WordJsonHandler { // 匯出 Word 至 JSON public void ExportJson(string wordFilePath, string jsonFilePath) { var paragraphs = new List(); using (var document = WordprocessingDocument.Open(wordFilePath, false)) { var body = document.MainDocumentPart.Document.Body; foreach (var paragraph in body.Elements()) { paragraphs.Add(paragraph.InnerText.Trim()); } } var options = new JsonSerializerOptions { WriteIndented = true }; string json = JsonSerializer.Serialize(paragraphs, options); File.WriteAllText(jsonFilePath, json, System.Text.Encoding.UTF8); Console.WriteLine($"已成功匯出 JSON 至 {jsonFilePath}"); } // 匯入 JSON 至 Word public void ImportJson(string jsonFilePath, string wordFilePath) { string json = File.ReadAllText(jsonFilePath, System.Text.Encoding.UTF8); var paragraphs = JsonSerializer.Deserialize>(json); using (var document = WordprocessingDocument.Create(wordFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { var mainPart = document.AddMainDocumentPart(); mainPart.Document = new Document(new Body()); foreach (var text in paragraphs) { var body = mainPart.Document.Body; var paragraph = new Paragraph(new Run(new Text(text))); body.AppendChild(paragraph); } mainPart.Document.Save(); } Console.WriteLine($"已成功匯入 JSON 至 Word,檔案儲存於 {wordFilePath}"); } } public class Program { public static void Main() { var handler = new WordJsonHandler(); // 匯出 Word 至 JSON handler.ExportJson("example.docx", "example.json"); // 匯入 JSON 至 Word handler.ImportJson("example.json", "new_example.docx"); } } ``` ### **程式說明** 1. **`ExportJson()` 函數**: - 使用 `OpenXml` SDK 讀取 Word 文件內容。 - 提取所有段落的純文字,並將其存入列表。 - 使用 `System.Text.Json` 將列表序列化為 JSON,並存為 UTF-8 格式檔案。 2. **`ImportJson()` 函數**: - 讀取 JSON 檔案並反序列化為段落文字列表。 - 使用 `OpenXml` SDK 創建新的 Word 文件。 - 將每一段文字新增為 Word 文件中的段落。 3. **必要套件**: - 安裝 `OpenXml` SDK: ```bash dotnet add package DocumentFormat.OpenXml ``` 4. **檔案格式**: - 匯出的 JSON 文件為 UTF-8 編碼,包含段落文字的列表。例如: ```json [ "This is the first paragraph.", "This is the second paragraph." ] ``` 5. **使用注意**: - 確保 Word 文件和 JSON 文件格式正確且符合使用情境。 - 若要處理更複雜的 Word 文件(如帶有樣式或圖片),需要進一步擴展程式邏輯。 如果需要進一步修改或擴展功能,隨時告訴我! 😊