Csharp: create word file using Open XML SDK 2.5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Spreadsheet;
using System.IO;
using System.IO.Packaging;
using System.Xml;
using System.Xml.Linq;
 
namespace OpenXmlOficeDemo
{
 
    /// <summary>
    ///Open XML SDK 2.0 WORD https://msdn.microsoft.com/en-us/library/office/gg490656(v=office.14).aspx
    ///Open XML SDK 2.5 WORD https://msdn.microsoft.com/en-us/library/office/ff478541.aspx
    /// </summary>
    public partial class Form2 : Form
    {
 
        /// <summary>
        ///
        /// </summary>
        public Form2()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form2_Load(object sender, EventArgs e)
        {
 
            //打开文档添加表格
            //string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            //string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "全国民代课教师的信息收集模板" + ".docx");  // "geovindu" + timeMark 
            //WDAddTable(fileName, new string[,]
            //  {
            //      { "涂聚文",  "Du" },
            //      { "Texas",  "TX" },
            //      { "California", "CA" },
            //      { "New York", "NY" },
            //      { "New York", "NY" },
            //      { "Massachusetts", "MA" }
            //  });
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // Change an existing property's value or create a new one with the supplied value
            WDSetCustomProperty("C:\\demo.docx", "Completed",false, PropertyTypes.YesNo);
 
            // Change an existing property's value or create a new one with the supplied value
            WDSetCustomProperty("C:\\demo.docx", "Completed",new DateTime(2008, 1, 1), PropertyTypes.DateTime);
 
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "geovindu" + timeMark + ".docx");
            CreateWordDoc(fileName, "geovin", new string[,]
              {
                  { "涂聚文""Du" },
                  { "Texas""TX" },
                  { "California", "CA" },
                  { "New York", "NY" },
                  { "New York", "NY" },
                  { "Massachusetts", "MA" }
              });
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static XElement WDRetrieveTOC(string fileName)
        {
            XElement TOC = null;
 
            using (var document = WordprocessingDocument.Open(fileName, false))
            {
                var docPart = document.MainDocumentPart;
                var doc = docPart.Document;
 
                OpenXmlElement block = doc.Descendants<DocPartGallery>().
                  Where(b => b.Val.HasValue &&
                    (b.Val.Value == "Table of Contents")).FirstOrDefault();
 
                if (block != null)
                {
                    // Back up to the enclosing SdtBlock and return that XML.
                    while ((block != null) && (!(block is SdtBlock)))
                    {
                        block = block.Parent;
                    }
                    TOC = new XElement("TOC", block.OuterXml);
                }
            }
            return TOC;
        }
        /// <summary>
        /// 打开WORD添加表格WORD   
        /// Take the data from a 2-dimensional array and build a table at the
        /// end of the supplied document.
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        public static void WDAddTable(string fileName, string[,] data)
        {
 
 
            using (var document =  WordprocessingDocument.Open(fileName, true))//WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
            {
 
                var doc = document.MainDocumentPart.Document;
 
                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
 
                TableProperties props = new TableProperties(
                  new TableBorders(
                    new DocumentFormat.OpenXml.Wordprocessing.TopBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.LeftBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.RightBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new InsideHorizontalBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new InsideVerticalBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    }));
                table.AppendChild<TableProperties>(props);
 
                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));
                        // Assume you want columns that are automatically sized.
                        tc.Append(new TableCellProperties(
                          new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                }
                doc.Body.Append(table);
                doc.Save();
            }
        }
 
        /// <summary>
        /// 创建WORD文档,添加表格
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        public static void CreateWordDoc(string filepath, string msg, string[,] data)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
                // Create the document structure and add some text.
                mainPart.Document = new Document();
                Body body = new Body(); //
                DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                TableProperties props = new TableProperties(
                  new TableBorders(
                    new DocumentFormat.OpenXml.Wordprocessing.TopBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.LeftBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.RightBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new InsideHorizontalBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new InsideVerticalBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    }));
                table.AppendChild<TableProperties>(props);
 
                for (var i = 0; i <= data.GetUpperBound(0); i++)
                {
                    var tr = new TableRow();
                    for (var j = 0; j <= data.GetUpperBound(1); j++)
                    {
                        var tc = new TableCell();
                        tc.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data[i, j]))));
                        // Assume you want columns that are automatically sized.
                        tc.Append(new TableCellProperties(
                          new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                }
 
                //appending table to body
                body.Append(table);
                // and body to the document
                mainPart.Document.Append(body);
                // Save changes to the main document part.
                mainPart.Document.Save();
  
            }
        
        }
 
        /// <summary>
        /// Delete headers and footers from a document.
        /// </summary>
        /// <param name="docName"></param>
        public static void WDRemoveHeadersFooters(string docName)
        {
            // Given a document name, remove all headers and footers.
            using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(docName, true))
            {
                var docPart = wdDoc.MainDocumentPart;
                if (docPart.HeaderParts.Count() > 0 || docPart.FooterParts.Count() > 0)
                {
                    // Remove header and footer parts.
                    docPart.DeleteParts(docPart.HeaderParts);
                    docPart.DeleteParts(docPart.FooterParts);
 
                    Document doc = docPart.Document;
 
                    // Remove references to the headers and footers.
                    // This requires digging into the XML content
                    // of the document:
                    var headers =
                      doc.Descendants<HeaderReference>().ToList();
                    foreach (var header in headers)
                    {
                        header.Remove();
                    }
 
                    var footers =
                      doc.Descendants<FooterReference>().ToList();
                    foreach (var footer in footers)
                    {
                        footer.Remove();
                    }
                    doc.Save();
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="txt"></param>
        public static void OpenAndAddTextToWordDocument(string filepath, string txt)
        {
            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);
 
            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
 
            // Add new text.
            Paragraph para = body.AppendChild(new Paragraph());
            DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
            run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(txt));
 
            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="msg"></param>
        public static void CreateWordDoc(string filepath, string msg)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part.
                MainDocumentPart mainPart = doc.AddMainDocumentPart();
 
                // Create the document structure and add some text.
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
 
                // String msg contains the text, "Hello, Word!"
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(msg));
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        public static void OpenWordprocessingDocumentReadonly(string filepath)
        {
            // Open a WordprocessingDocument based on a filepath.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(filepath, false))
            {
                // Assign a reference to the existing document body. 
                Body body = wordDocument.MainDocumentPart.Document.Body;
 
                // Attempt to add some text.
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly"));
 
                // Call Save to generate an exception and show that access is read-only.
                // wordDocument.MainDocumentPart.Document.Save();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        public static void OpenWordprocessingPackageReadonly(string filepath)
        {
            // Open System.IO.Packaging.Package.
            Package wordPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read);
 
            // Open a WordprocessingDocument based on a package.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(wordPackage))
            {
                // Assign a reference to the existing document body.
                Body body = wordDocument.MainDocumentPart.Document.Body;
 
                // Attempt to add some text.
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Append text in body, but text is not saved - OpenWordprocessingPackageReadonly"));
 
                // Call Save to generate an exception and show that access is read-only.
                // wordDocument.MainDocumentPart.Document.Save();
            }
 
            // Close the package.
            wordPackage.Close();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="filepath"></param>
        public static void CreateSpreadsheetWorkbook(string filepath)
        {
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
 
            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();
 
            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());
 
            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
 
            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);
 
            workbookpart.Workbook.Save();
 
            // Close the document.
            spreadsheetDocument.Close();
        }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/// <summary>
        ///
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="destinationFile"></param>
        private void setWord(string sourceFile, string destinationFile)
        {
            File.Copy(sourceFile, destinationFile, true);
            using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true))
            {
                // Change the document type to Document  DocumentFormat.OpenXml.WordprocessingDocumentType
 
               // DocumentFormat.OpenXml.WordprocessingDocumentType doc = new WordprocessingDocumentType(); 
                 document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
                // Get the MainPart of the document
                MainDocumentPart mainPart = document.MainDocumentPart;
                // Get the Document Settings Part
                DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
                // Create a new attachedTemplate and specify a relationship ID
                AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" };
                // Append the attached template to the DocumentSettingsPart
                documentSettingPart1.Settings.Append(attachedTemplate1);
                // Add an ExternalRelationShip of type AttachedTemplate.
                // Specify the path of template and the relationship
                documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(sourceFile, UriKind.Absolute), "relationId1");
 
                // Get a list of bookmarks
                IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();
                foreach (BookmarkStart bookmarkStart in mainPart.RootElement.Descendants<BookmarkStart>())
                {
                    bookmarkMap[bookmarkStart.Name] = bookmarkStart;
                }
                // Make changes to bookmarks
                foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
                {
                    if (bookmarkStart.Name == "WorkOrderNo")
                    {
                        string WorkOrderNum = "WorkOrderNo";
                        DocumentFormat.OpenXml.Wordprocessing.Text text = new DocumentFormat.OpenXml.Wordprocessing.Text(WorkOrderNum);
                        DocumentFormat.OpenXml.Wordprocessing.FontSize WOFontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
                        WOFontSize.Val = "28";
                        DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.Bold(), WOFontSize));
                        run.Append(text);
                        bookmarkStart.InsertAfterSelf(run);
                    }
                    else if (bookmarkStart.Name == "BillingCode")
                    {
                        string BillingCode = "BillingCode";
                        DocumentFormat.OpenXml.Wordprocessing.Text text = new DocumentFormat.OpenXml.Wordprocessing.Text(BillingCode);
                        DocumentFormat.OpenXml.Wordprocessing.FontSize WOFontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
                        WOFontSize.Val = "28";
                        DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.Bold(), WOFontSize));
                        run.Append(text);
                        bookmarkStart.InsertAfterSelf(run);
                    }
                }
                // Save the document
                mainPart.Document.Save();
            }
        }
        /// <summary>
        /// To search and replace content in a document part.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="dict"></param>
        public static void SearchAndReplace(string document, Dictionary<string, string> dict)
        {
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
            {
                string docText = null;
                using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
                {
                    docText = sr.ReadToEnd();
                }
 
                foreach (KeyValuePair<string, string> item in dict)
                {
                    Regex regexText = new Regex(item.Key);
                    docText = regexText.Replace(docText, item.Value);
                }
 
                using (StreamWriter sw = new StreamWriter(
                          wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
                {
                    sw.Write(docText);
                }
 
            }
        }

  

posted @   ®Geovin Du Dream Park™  阅读(620)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2011-08-21 sql ntext數據類型字符替換
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示