服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#生成Word文件(图片、文字)

C#生成Word文件(图片、文字)

2022-07-24 17:43Daniel799 C#

这篇文章主要为大家详细介绍了C#生成Word文件,包括图片、文字等素材,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C#生成Word文件的具体代码,供大家参考,具体内容如下

通过Microsoft.Office.Interop.Word生成Word文档

1.引用类 WordReport.cs,代码如下:

?
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
431
432
433
434
435
436
437
438
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
using MSWord = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.IO;
 
namespace CRM.Common
{
  public class WordReport
  {
    private _Application wordApp = null;
    private _Document wordDoc = null;
    object unite = MSWord.WdUnits.wdStory;
    Object Nothing = Missing.Value;
    public _Application Application
    {
      get
      {
        return wordApp;
      }
      set
      {
        wordApp = value;
      }
    }
    public _Document Document
    {
      get
      {
        return wordDoc;
      }
      set
      {
        wordDoc = value;
      }
    }
 
    // 通过模板创建新文档
    public void CreateNewDocument(string filePath)
    {
      try
      {
        killWinWordProcess();
        wordApp = new ApplicationClass();
        wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApp.Visible = false;
        object missing = System.Reflection.Missing.Value;
        object templateName = filePath;
        wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
          ref missing, ref missing, ref missing, ref missing, ref missing,
          ref missing, ref missing, ref missing, ref missing, ref missing,
          ref missing, ref missing, ref missing, ref missing);
      }
      catch (Exception ex)
      {
        
      }
    }
    public void CreateNewDocument()
    {
      try
      {
        //killWinWordProcess();
        wordApp = new ApplicationClass();
        wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
        wordApp.Visible = false;
        Object Nothing = Missing.Value;
        wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
      }
      catch (Exception ex)
      {
        
      }
    }
    // 保存新文件
    public void SaveDocument(string filePath)
    {
      if (File.Exists((string)filePath))
      {
        File.Delete((string)filePath);
      }
      object fileName = filePath;
      object format = WdSaveFormat.wdFormatDocument;//保存格式
      object miss = System.Reflection.Missing.Value;
      wordDoc.SaveAs(ref fileName, ref format, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss, ref miss, ref miss, ref miss,
        ref miss);
      //关闭wordDoc,wordApp对象
      object SaveChanges = WdSaveOptions.wdSaveChanges;
      object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
      object RouteDocument = false;
      wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
      wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
    }
    public void InsertText(string strContent)
    {
      //写入普通文本
      wordDoc.Content.InsertAfter(strContent);
      wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
 
      
    }
    public void InsertTitle(string strContent)
    {
      //写入普通文本
      wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
 
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("标题 5");
      }
      catch (Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Heading 5");
      }
      wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;
      wordDoc.Paragraphs.Last.Range.Font.Size = 11;
      wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
      wordDoc.Paragraphs.Last.Range.Text = strContent;
      wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Normal");
      }
      catch (Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("正文");
      }
 
 
    }
    // 在书签处插入值
    public bool InsertValue(string bookmark, string value)
    {
      object bkObj = bookmark;
      if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
      {
        wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
        wordApp.Selection.TypeText(value);
        return true;
      }
      return false;
    }
 
    // 插入表格,bookmark书签
    public Table InsertTable(string bookmark, int rows, int columns, float width)
    {
      object miss = System.Reflection.Missing.Value;
      object oStart = bookmark;
      Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
      Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
      //设置表的格式
      newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)
      newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度
      if (width != 0)
      {
        newTable.PreferredWidth = width;//表格宽度
      }
      newTable.AllowPageBreaks = false;
      return newTable;
    }
 
 
    // 合并单元格 表id,开始行号,开始列号,结束行号,结束列号
    public void MergeCell(int n, int row1, int column1, int row2, int column2)
    {
      wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
    }
 
    // 合并单元格 表名,开始行号,开始列号,结束行号,结束列号
    public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
    {
      table.Cell(row1, column1).Merge(table.Cell(row2, column2));
    }
 
    // 设置表格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)Microsoft.Office.Interop.Word.Table table
    public void SetParagraph_Table(int n, int Align, int Vertical)
    {
      switch (Align)
      {
        case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
        case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
        case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
      }
      switch (Vertical)
      {
        case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
        case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
        case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
      }
    }
 
    // 设置单元格内容对齐方式
    public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical)
    {
      switch (Align)
      {
        case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
        case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
        case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
      }
      switch (Vertical)
      {
        case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
        case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
        case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
      }
 
    }
 
 
    // 设置表格字体
    public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)
    {
      if (size != 0)
      {
        table.Range.Font.Size = Convert.ToSingle(size);
      }
      if (fontName != "")
      {
        table.Range.Font.Name = fontName;
      }
    }
 
    // 设置单元格字体
    public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold)
    {
      if (size != 0)
      {
        wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size);
      }
      if (fontName != "")
      {
        wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName;
      }
      wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗体,其他值都是
    }
 
    // 是否使用边框,n表格的序号,use是或否
    // 该处边框参数可以用int代替bool可以让方法更全面
    // 具体值方法中介绍
    public void UseBorder(int n, bool use)
    {
      if (use)
      {
        wordDoc.Content.Tables[n].Borders.Enable = 1;
        //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
      }
      else
      {
        wordDoc.Content.Tables[n].Borders.Enable = 0;
      }
    }
 
    // 给表格插入一行,n表格的序号从1开始记
    public void AddRow(int n)
    {
      object miss = System.Reflection.Missing.Value;
      wordDoc.Content.Tables[n].Rows.Add(ref miss);
    }
 
    // 给表格添加一行
    public void AddRow(Microsoft.Office.Interop.Word.Table table)
    {
      object miss = System.Reflection.Missing.Value;
      table.Rows.Add(ref miss);
    }
 
    // 给表格插入rows行,n为表格的序号
    public void AddRow(int n, int rows)
    {
      object miss = System.Reflection.Missing.Value;
      Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
      for (int i = 0; i < rows; i++)
      {
        table.Rows.Add(ref miss);
      }
    }
 
    // 删除表格第rows行,n为表格的序号
    public void DeleteRow(int n, int row)
    {
      Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
      table.Rows[row].Delete();
    }
 
    // 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素
    public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
    {
      table.Cell(row, column).Range.Text = value;
    }
 
    // 给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素
    public void InsertCell(int n, int row, int column, string value)
    {
      wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
    }
 
    // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
    public void InsertCell(int n, int row, int columns, string[] values)
    {
      Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
      for (int i = 0; i < columns; i++)
      {
        table.Cell(row, i + 1).Range.Text = values[i];
      }
    }
 
    // 插入图片
    public void InsertPicture(string bookmark, string picturePath, float width, float hight)
    {
      object miss = System.Reflection.Missing.Value;
      object oStart = bookmark;
      Object linkToFile = false;    //图片是否为外部链接
      Object saveWithDocument = true; //图片是否随文档一起保存
      object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
      wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
      wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width;  //设置图片宽度
      wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //设置图片高度
    }
    public void InsertPicture(string picturePath, float width, float hight,WdParagraphAlignment align)
    {
      object unite = MSWord.WdUnits.wdStory;
      Object Nothing = Missing.Value;
      Application.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
      //要向Word文档中插入图片的位置
      Object range = wordDoc.Paragraphs.Last.Range;
      //定义该插入的图片是否为外部链接
      Object linkToFile = false;        //默认,这里貌似设置为bool类型更清晰一些
      //定义要插入的图片是否随Word文档一起保存
      Object saveWithDocument = true;       //默认
      //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入图片
      InlineShape shape = wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
      wordApp.Selection.ParagraphFormat.Alignment = align;//
      
      //设置图片宽高的绝对大小
      if (width!=-1)
        wordDoc.InlineShapes[1].Width = width;
      if(hight!=-1)
        wordDoc.InlineShapes[1].Height = hight;
      try
      {
        wordDoc.Paragraphs.Last.Range.set_Style("正文");
      }
      catch(Exception ex)
      {
        wordDoc.Paragraphs.Last.Range.set_Style("Normal");
      }  
      shape.Borders.Enable = 12;
    
      //shape.ConvertToShape().WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;//四周环绕的方式
    }
 
    // 插入一段文字,text为文字内容
    public void InsertText(string bookmark, string text)
    {
      object oStart = bookmark;
      object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
      Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
      wp.Format.SpaceBefore = 6;
      wp.Range.Text = text;
      wp.Format.SpaceAfter = 24;
      wp.Range.InsertParagraphAfter();
      wordDoc.Paragraphs.Last.Range.Text = "\n";
    }
 
    // 杀掉winword.exe进程
    public void killWinWordProcess()
    {
      System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
      foreach (System.Diagnostics.Process process in processes)
      {
        bool b = process.MainWindowTitle == "";
        if (process.MainWindowTitle == "")
        {
          process.Kill();
        }
      }
    }
 
 
 
    internal void InsertTable(int tableRow, int tableColumn,List<string> imagePaths)
    {
      wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
      MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
                          tableRow, tableColumn, ref Nothing, ref Nothing);
 
      //默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
      table.Borders.Enable = 0;//这个值可以设置得很大,例如5、13等等
 
      //表格的索引是从1开始的。
      for (int i = 1; i <= tableRow; i++)
      {
        for (int j = 1; j <= tableColumn; j++)
        {
          
          int index = (i-1) * tableColumn + j-1;
          if (index < imagePaths.Count)//有文件
          {
            string FileName = imagePaths[index]; //图片所在路径
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = table.Cell(i, j).Range;//选中要添加图片的单元格
            MSWord.InlineShape il = wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
 
            //图片大小
            il.Width = 100;//图片宽度
            il.Height = 100;//图片高度
            table.Rows[i].Cells[j].Split(2, 1);
            table.Cell(i+1, j).Range.Text = "图片名称:"+(index+1).ToString(); //
            table.Cell(i+1, j).Merge(table.Cell(i, j));//纵向合并
          }
        }
      }
      //设置table样式
      table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度规则是:行高有最低值下限?
      table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));//
 
      table.Range.Font.Size = 10.5F;
      table.Range.Font.Bold = 0;
 
      table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中
      table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直贴到底部
      //设置table边框样式
      table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格外框是双线
      table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格内框是单线
 
      table.Rows[1].Range.Font.Bold = 1;//加粗
      table.Rows[1].Range.Font.Size = 12F;
      table.Cell(1, 1).Range.Font.Size = 10.5F;
    }
  }
}

2.生成Word文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/// <summary>
///
/// </summary>
/// <param name="path">like string path=@"c:\\temp\\"</param>
public void GengerateWord(string path)
    {
      string fileName = "test.doc";
      WordReport report = new WordReport();
      report.CreateNewDocument(); //创建文件
      report.InsertTitle("标题");
      float width = 420;//图片宽度
      float height = 200;//图片高度
      report.InsertPicture("图片地址", width, height, WdParagraphAlignment.wdAlignParagraphCenter);
      report.SaveDocument(path+ fileName);
}

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u012664198/article/details/90411717

延伸 · 阅读

精彩推荐
  • C#C#图片切割、图片压缩、缩略图生成代码汇总

    C#图片切割、图片压缩、缩略图生成代码汇总

    这篇文章主要为大家汇总了C#图片切割、图片压缩、缩略图生成代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    李朝强7502021-11-21
  • C#详解C#实现MD5加密的示例代码

    详解C#实现MD5加密的示例代码

    本篇文章主要介绍了C#实现MD5加密的示例代码,详细的介绍了几种方法,具有一定的参考价值,有兴趣的可以了解一下。...

    shenghui1884582021-12-16
  • C#详解C#批量插入数据到Sqlserver中的四种方式

    详解C#批量插入数据到Sqlserver中的四种方式

    本文主要讲解一下在Sqlserver中批量插入数据。文中大数据批量插入方式一和方式四尽量避免使用,而方式二和方式三都是非常高效的批量插入数据方式,需...

    邹琼俊7802021-12-14
  • C#C#将Excel转成PDF的方法

    C#将Excel转成PDF的方法

    今天小编就为大家分享一篇关于C#将Excel转成PDF的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧...

    chenqiangdage7452022-03-08
  • C#c#汉诺塔的递归算法与解析

    c#汉诺塔的递归算法与解析

    c#汉诺塔的递归算法与解析,需要的朋友可以参考一下...

    C#教程网2132020-12-18
  • C#C# 通过 oledb 操作Excel实例代码

    C# 通过 oledb 操作Excel实例代码

    本篇文章主要介绍了C# 通过 oledb 操作Excel实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    李子康3712022-01-06
  • C#C#简单实现防止多个程序运行的方法

    C#简单实现防止多个程序运行的方法

    这篇文章主要介绍了C#简单实现防止多个程序运行的方法,涉及C#进程操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    Microblue4522021-11-14
  • C#C#实现向多线程传参的三种方式实例分析

    C#实现向多线程传参的三种方式实例分析

    这篇文章主要介绍了C#实现向多线程传参的三种方式,以实例形式较为详细的分析了C#多线程及参数传递的相关技巧,具有一定参考借鉴价值,需要的朋友可以参...

    lexiaoyao2011702021-11-02