当前位置:   article > 正文

c#&word文档:3.向Word文档中插入表格/4.读取Word文档中表格

c#&word文档:3.向Word文档中插入表格/4.读取Word文档中表格
 --向Word文档中插入表格--

(1)在OfficeOperator项目的WordOperator类中定义向Word文档插入换页的函数NewPage

(2)在WordOperator类中定义向Word文档插入表格的函数InsertTable

  1. using Microsoft.Office.Interop.Word;// 引入Microsoft.Office.Interop.Word命名空间
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace OfficeOperator1
  9. {
  10. public class WordOperator1
  11. {
  12. //为WordOperator1声明两个操作Word文档的私有对象
  13. Application WordApp; //Word应用对象
  14. Document WordDoc; //Word文档对象
  15. public WordOperator1() //在WordOperator1的构造函数中创建WordApp
  16. {
  17. WordApp = new Application(); //创建Word应用对象
  18. WordApp.Visible = true; //创建完成后是否显示Word文档
  19. }
  20. //定义用于创建Word文档的函数CreateWord,代码如下:
  21. public void CreateWord()//创建Word文档
  22. {
  23. WordDoc = WordApp.Documents.Add(); //创建Word文档对象
  24. WordDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait; //横板还是竖板
  25. WordDoc.PageSetup.LeftMargin = WordApp.CentimetersToPoints(0.5f); //左边距
  26. WordDoc.PageSetup.RightMargin = WordApp.CentimetersToPoints(0.5f); //右边距
  27. WordDoc.PageSetup.TopMargin = WordApp.CentimetersToPoints(0.5f); //上边距
  28. WordDoc.PageSetup.BottomMargin = WordApp.CentimetersToPoints(0.5f); //下边距
  29. WordDoc.PageSetup.PageWidth = 400; //页宽,单位:像素
  30. WordDoc.PageSetup.PageHeight = 600; //页高,单位:像素
  31. }
  32. public void SaveWord(string fileName)//文档保存
  33. {
  34. object FileName = fileName; //文档名称
  35. object FileFormat = WdSaveFormat.wdFormatDocument; //Word文档保存格式
  36. object LockComments = false; //是否锁定批注
  37. object Password = ""; //打开Word文档密码
  38. object WritePassword = ""; //修改Word文档密码
  39. object AddToRecentFiles = true; //是否将文档添加到近期使用的文件菜单中
  40. WordDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword); //保存Word文档
  41. }
  42. public void QuitWord()//关闭Word文档
  43. {
  44. ((_Document)WordDoc).Close(); //关闭Word文档
  45. ((_Application)WordApp).Quit(); //退出Word应用
  46. }
  47. //退出Word应用程序
  48. public void SetPageHeader(string Text)//页眉中添加文字
  49. {
  50. WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; //设置视图类型
  51. WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;//选定页眉
  52. WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(Text);//向页眉中添加文字
  53. WordApp.Selection.ParagraphFormat.Alignment = //设置居中对齐
  54. WdParagraphAlignment.wdAlignParagraphCenter;
  55. WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//选定主文档
  56. }
  57. public void SetPageFooter(string Text)//页脚中添加文字
  58. {
  59. WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; //设置视图类型
  60. WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;//选定页脚
  61. WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(Text); //向页脚中添加文字
  62. WordApp.Selection.ParagraphFormat.Alignment = //设置居中对齐
  63. WdParagraphAlignment.wdAlignParagraphCenter;
  64. WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; //选定主文档
  65. }
  66. /// <summary>
  67. /// 设置页码
  68. /// </summary>
  69. /// <param name="isFirstPage"></param>
  70. public void InsertPageNumber(bool isFirstPage)
  71. {
  72. object Alignment = WdPageNumberAlignment.wdAlignPageNumberRight;//页码对齐方式
  73. object IsFirstPage = isFirstPage; //是否从首页开始
  74. //对所有的页眉和页脚设置页码
  75. WdHeaderFooterIndex WdFooterIndex = WdHeaderFooterIndex.wdHeaderFooterPrimary;
  76. WordApp.Selection.Sections[1].Footers[WdFooterIndex].PageNumbers.Add
  77. (ref Alignment, ref IsFirstPage);
  78. }
  79. /// <summary>
  80. /// Word文档添加文字
  81. /// </summary>
  82. /// <param name="Text"></param>
  83. /// <param name="FontSize"></param>
  84. /// <param name="FontColor"></param>
  85. /// <param name="FontBold"></param>
  86. /// <param name="TextAlignment"></param>
  87. /// <param name="FontName"></param>
  88. public void InsertText(string Text, int FontSize, WdColor FontColor, int FontBold,
  89. WdParagraphAlignment TextAlignment, string FontName)
  90. {
  91. WordApp.Application.Selection.Font.Size = FontSize; //字体大小
  92. WordApp.Application.Selection.Font.Bold = FontBold; //是否粗体,0-否,1-是
  93. WordApp.Application.Selection.Font.Color = FontColor; //字体颜色
  94. WordApp.Application.Selection.ParagraphFormat.Alignment = TextAlignment; //字体排布
  95. WordApp.Application.Selection.Font.Name = FontName; //字体名称
  96. WordApp.Application.Selection.TypeText(Text); //文字内容
  97. }
  98. /// <summary>
  99. /// 换行
  100. /// </summary>
  101. public void NewLine()
  102. {
  103. WordApp.Application.Selection.TypeParagraph(); //换行
  104. }
  105. /// <summary>
  106. /// 向Word文档中插入图片
  107. /// </summary>
  108. /// <param name="FileName"></param>
  109. /// <param name="Width"></param>
  110. /// <param name="Height"></param>
  111. public void InsertPicture(string FileName, int Width, int Height)
  112. {
  113. object LinkToFile = false; //是否连接到文件
  114. object SaveWithDocument = true; //是否保存到文档中
  115. object Range = System.Reflection.Missing.Value;
  116. WordApp.Selection.ParagraphFormat.Alignment = //设置段落对齐方式
  117. WdParagraphAlignment.wdAlignParagraphCenter;
  118. InlineShape inlineShape = WordDoc.Application.Selection.InlineShapes.
  119. AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range); //添加图片
  120. if (Width != 0 || Height != 0)
  121. {
  122. inlineShape.Width = Width; //设置图像宽度
  123. inlineShape.Height = Height; //设置图像高度
  124. }
  125. }
  126. /// <summary>
  127. /// 换页
  128. /// </summary>
  129. public void NewPage()
  130. {
  131. object BreakType = WdBreakType.wdSectionBreakNextPage; //换页
  132. WordDoc.Application.Selection.InsertBreak(ref BreakType); //插入换页
  133. }
  134. /// <summary>
  135. /// 添加表格
  136. /// </summary>
  137. /// <param name="dataSet"></param>
  138. public void InsertTable(DataSet dataSet)
  139. {
  140. WordDoc.Tables.Add(WordApp.Selection.Range, //添加表格
  141. dataSet.Tables[0].Rows.Count, dataSet.Tables[0].Columns.Count);
  142. WordDoc.Tables[1].Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast; //行高规则
  143. WordDoc.Tables[1].Rows.Height = WordApp.CentimetersToPoints(0.8f);//设置行高
  144. WordDoc.Tables[1].Range.Font.Size = 10; //设置字体大小
  145. WordDoc.Tables[1].Range.Font.Name = "宋体"; //设置字体类型
  146. WordDoc.Tables[1].Range.ParagraphFormat.Alignment = //设置段落对齐
  147. WdParagraphAlignment.wdAlignParagraphCenter;
  148. WordDoc.Tables[1].Range.Cells.VerticalAlignment = //设置表格元素垂直对齐
  149. WdCellVerticalAlignment.wdCellAlignVerticalCenter;
  150. WordDoc.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle = //设置左边框
  151. WdLineStyle.wdLineStyleDouble;
  152. WordDoc.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle = //设置右边框
  153. WdLineStyle.wdLineStyleDouble;
  154. WordDoc.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle = //设置上边框
  155. WdLineStyle.wdLineStyleDouble;
  156. WordDoc.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle = //设置下边框
  157. WdLineStyle.wdLineStyleDouble;
  158. WordDoc.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = //设置水平边框
  159. WdLineStyle.wdLineStyleSingle;
  160. WordDoc.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle = //设置垂直边框
  161. WdLineStyle.wdLineStyleSingle;
  162. //将数据集中的数据填充到表格中
  163. for (int i = 1; i <= dataSet.Tables[0].Rows.Count; i++)
  164. {
  165. for (int j = 1; j <= dataSet.Tables[0].Columns.Count; j++)
  166. {
  167. WordDoc.Tables[1].Cell(i, j).Range.Text = dataSet.Tables[0].Rows[i - 1][j - 1].ToString();
  168. }
  169. }
  170. }
  171. }
  172. }

 (3)将数据库中的学生信息表添加到Word文档中。在CreateWord项目的main函数中添加代码如下:

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM student_info", 
         "Data Source=.\\SQLEXPRESS;Initial Catalog=student;Integrated Security=True");
     DataSet dataSet = new DataSet();
     adapter.Fill(dataSet);                                                     //填充数据集
     word.InsertTable(dataSet);                                         //插入表格

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.SqlClient;
  4. using System.Data;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using Microsoft.Office.Interop.Word;
  10. using OfficeOperator1;
  11. namespace CreateWord1
  12. { internal class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. WordOperator1 word = new WordOperator1();
  17. word.CreateWord(); //创建Word文档
  18. word.SetPageHeader("C#经典实例"); //添加页眉
  19. word.SetPageFooter("第17章 访问office"); //添加页脚
  20. word.InsertPageNumber(true);                                          //添加页码
  21. word.InsertText("Word文档创建成功!", 16, WdColor.wdColorBlack, 1,
  22. WdParagraphAlignment.wdAlignParagraphCenter, "宋体"); //添加文字
  23. word.NewLine(); //换行
  24. word.InsertText("Word文档创建成功!", 18, WdColor.wdColorRed, 0,
  25. WdParagraphAlignment.wdAlignParagraphDistribute, "黑体"); //添加文字
  26. word.InsertPicture(Directory.GetCurrentDirectory() + "\\189.png", 100, 75);
  27. //添加图片
  28. SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM staq_info",
  29. "Data Source=.\\SQLEXPRESS;Initial Catalog=aq;Integrated Security=True");
  30. DataSet dataSet = new DataSet();
  31. adapter.Fill(dataSet); //填充数据集
  32. word.InsertTable(dataSet); //插入表格
  33. word.SaveWord(Directory.GetCurrentDirectory() + "\\测试文档11.doc");//保存Word文档
  34. word.QuitWord();
  35. }
  36. }
  37. }

代码中的aq是数据库,staq是数据表格 ,具体参考数据库章节/两篇代码汇总了word1-3章节

启动CreateWord的控制台应用程序:

--读取Word文档中表格 --

【实现过程】
(1)在OfficeOperator项目的WordOperator类中定义打开Word文档的函数OpenWord

public void OpenWord(string fileName)
     {
         object FileName = fileName;                            //Word文档文件名称
         WordDoc = WordApp.Documents.Open(ref FileName);        //打开Word文档
     }

(2)在WordOperator类中定义读取Word文档中表格的函数ReadTable,代码如下:

 public string ReadTable()
 {
     string stringTable = string.Empty;
     foreach (Table table in WordDoc.Tables)
     {//遍历Word文档中的表格
         for (int row = 1; row <= table.Rows.Count; row++)
         {//遍历表格中的行
             for (int column = 1; column <= table.Columns.Count; column++)
             {//遍历表格中的列
                 stringTable += table.Cell(row, column).Range.Text;//读取表格元素
                 stringTable = stringTable.Remove(stringTable.Length - 2, 2);//删除\r\a
                 stringTable += "\t";
             }
             stringTable += "\n";
         }
     }
     return stringTable;
 }

(3)创建一个名为OpenWord的控制台应用程序,为其添加对OfficeOperator项目的引用

  1. using OfficeOperator1;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace OpenWord
  9. {
  10. internal class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. WordOperator1 word = new WordOperator1();
  15. word.OpenWord(Directory.GetCurrentDirectory() + "\\测试文档.doc"); //打开Word文档
  16. Console.WriteLine(word.ReadTable()); //读取Word文档中的表格
  17. word.QuitWord();
  18. Console.ReadKey();
  19. }
  20. }
  21. }

(4)在程序路径准备 测试文档.doc(这里是上一章创建保存的文档复制过来):

 启动OpenWord的控制台应用程序:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/540902
推荐阅读