1. 1 using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using Microsoft.Office.Interop.Word;
  9.  
  10. namespace QHRMS // 根据自己需要修改命名空间
  11. {
  12. public class CreateWordHelper
  13. {
  14. private _Application wordApp = null;
  15. private _Document wordDoc = null;
  16. public _Application Application
  17. {
  18. get
  19. {
  20. return wordApp;
  21. }
  22. set
  23. {
  24. wordApp = value;
  25. }
  26. }
  27. public _Document Document
  28. {
  29. get
  30. {
  31. return wordDoc;
  32. }
  33. set
  34. {
  35. wordDoc = value;
  36. }
  37. }
  38.  
  39. // 通过模板创建新文档
  40. public bool CreateNewDocument(string filePath)
  41. {
  42. try
  43. {
  44.  
  45. killWinWordProcess();
  46. //wordApp=new Microsoft.Office.Interop.Word.Application();
  47. wordApp = new ApplicationClass();
  48. wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
  49. wordApp.Visible = false;
  50. object missing = System.Reflection.Missing.Value;
  51. object templateName = filePath;
  52. wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
  53. ref missing, ref missing, ref missing, ref missing, ref missing,
  54. ref missing, ref missing, ref missing, ref missing, ref missing,
  55. ref missing, ref missing, ref missing, ref missing);
  56. return true;
  57. }
  58. catch (Exception ex)
  59. {
  60. System.Windows.Forms.MessageBox.Show(ex.Message);
  61. return false;
  62. }
  63. }
  64.  
  65. // 保存新文件
  66. public void SaveDocument(string filePath)
  67. {
  68. object fileName = filePath;
  69. object format = WdSaveFormat.wdFormatDocument;//保存格式
  70. object miss = System.Reflection.Missing.Value;
  71. wordDoc.SaveAs(ref fileName, ref format, ref miss,
  72. ref miss, ref miss, ref miss, ref miss,
  73. ref miss, ref miss, ref miss, ref miss,
  74. ref miss, ref miss, ref miss, ref miss,
  75. ref miss);
  76. //关闭wordDoc,wordApp对象
  77. object SaveChanges = WdSaveOptions.wdSaveChanges;
  78. object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
  79. object RouteDocument = false;
  80. wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
  81. wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
  82. }
  83.  
  84. // 在书签处插入值
  85. public bool InsertValue(string bookmark, string value)
  86. {
  87. object bkObj = bookmark;
  88. if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
  89. {
  90. wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
  91. wordApp.Selection.TypeText(value);
  92. return true;
  93. }
  94. return false;
  95. }
  96.  
  97. // 插入表格,bookmark书签
  98. public Table InsertTable(string bookmark, int rows, int columns, float width)
  99. {
  100. object miss = System.Reflection.Missing.Value;
  101. object oStart = bookmark;
  102. Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
  103. Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
  104. //设置表的格式
  105. newTable.Borders.Enable = ; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)
  106. newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度
  107. if (width != )
  108. {
  109. newTable.PreferredWidth = width;//表格宽度
  110. }
  111. newTable.AllowPageBreaks = false;
  112. return newTable;
  113. }
  114.  
  115. // 合并单元格 表id,开始行号,开始列号,结束行号,结束列号
  116. public void MergeCell(int n, int row1, int column1, int row2, int column2)
  117. {
  118. wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
  119. }
  120.  
  121. // 合并单元格 表名,开始行号,开始列号,结束行号,结束列号
  122. public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
  123. {
  124. table.Cell(row1, column1).Merge(table.Cell(row2, column2));
  125. }
  126.  
  127. // 设置表格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)Microsoft.Office.Interop.Word.Table table
  128. public void SetParagraph_Table(int n, int Align, int Vertical)
  129. {
  130. switch (Align)
  131. {
  132. case -: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
  133. case : wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
  134. case : wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
  135. }
  136. switch (Vertical)
  137. {
  138. case -: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
  139. case : wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
  140. case : wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
  141. }
  142. }
  143.  
  144. // 设置单元格内容对齐方式
  145. public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical)
  146. {
  147. switch (Align)
  148. {
  149. case -: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
  150. case : wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
  151. case : wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
  152. }
  153. switch (Vertical)
  154. {
  155. case -: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
  156. case : wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
  157. case : wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
  158. }
  159.  
  160. }
  161.  
  162. // 设置表格字体
  163. public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)
  164. {
  165. if (size != )
  166. {
  167. table.Range.Font.Size = Convert.ToSingle(size);
  168. }
  169. if (fontName != "")
  170. {
  171. table.Range.Font.Name = fontName;
  172. }
  173. }
  174.  
  175. // 设置单元格字体
  176. public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold)
  177. {
  178. if (size != )
  179. {
  180. wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size);
  181. }
  182. if (fontName != "")
  183. {
  184. wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName;
  185. }
  186. wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗体,其他值都是
  187. }
  188.  
  189. // 是否使用边框,n表格的序号,use是或否
  190. // 该处边框参数可以用int代替bool可以让方法更全面
  191. // 具体值方法中介绍
  192. public void UseBorder(int n, bool use)
  193. {
  194. if (use)
  195. {
  196. wordDoc.Content.Tables[n].Borders.Enable = ;
  197. //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
  198. }
  199. else
  200. {
  201. wordDoc.Content.Tables[n].Borders.Enable = ;
  202. }
  203. }
  204.  
  205. // 给表格插入一行,n表格的序号从1开始记
  206. public void AddRow(int n)
  207. {
  208. object miss = System.Reflection.Missing.Value;
  209. wordDoc.Content.Tables[n].Rows.Add(ref miss);
  210. }
  211.  
  212. // 给表格添加一行
  213. public void AddRow(Microsoft.Office.Interop.Word.Table table)
  214. {
  215. object miss = System.Reflection.Missing.Value;
  216. table.Rows.Add(ref miss);
  217. }
  218.  
  219. // 给表格插入rows行,n为表格的序号
  220. public void AddRow(int n, int rows)
  221. {
  222. object miss = System.Reflection.Missing.Value;
  223. Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  224. for (int i = ; i < rows; i++)
  225. {
  226. table.Rows.Add(ref miss);
  227. }
  228. }
  229.  
  230. // 删除表格第rows行,n为表格的序号
  231. public void DeleteRow(int n, int row)
  232. {
  233. Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  234. table.Rows[row].Delete();
  235. }
  236.  
  237. // 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素
  238. public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
  239. {
  240. table.Cell(row, column).Range.Text = value;
  241. }
  242.  
  243. // 给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素
  244. public void InsertCell(int n, int row, int column, string value)
  245. {
  246. wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
  247. }
  248.  
  249. // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
  250. public void InsertCell(int n, int row, int columns, string[] values)
  251. {
  252. Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  253. for (int i = ; i < columns; i++)
  254. {
  255. table.Cell(row, i + ).Range.Text = values[i];
  256. }
  257. }
  258.  
  259. // 插入图片
  260. public void InsertPicture(string bookmark, string picturePath, float width, float hight)
  261. {
  262. object miss = System.Reflection.Missing.Value;
  263. object oStart = bookmark;
  264. Object linkToFile = false; //图片是否为外部链接
  265. Object saveWithDocument = true; //图片是否随文档一起保存
  266. object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
  267. wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
  268. wordDoc.Application.ActiveDocument.InlineShapes[].Width = width; //设置图片宽度
  269. wordDoc.Application.ActiveDocument.InlineShapes[].Height = hight; //设置图片高度
  270. }
  271.  
  272. // 插入一段文字,text为文字内容
  273. public void InsertText(string bookmark, string text)
  274. {
  275. object oStart = bookmark;
  276. object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
  277. Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
  278. wp.Format.SpaceBefore = ;
  279. wp.Range.Text = text;
  280. wp.Format.SpaceAfter = ;
  281. wp.Range.InsertParagraphAfter();
  282. wordDoc.Paragraphs.Last.Range.Text = "\n";
  283. }
  284.  
  285. // 杀掉winword.exe进程
  286. public void killWinWordProcess()
  287. {
  288. System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
  289. foreach (System.Diagnostics.Process process in processes)
  290. {
  291. bool b = process.MainWindowTitle == "";
  292. if (process.MainWindowTitle == "")
  293. {
  294. process.Kill();
  295. }
  296. }
  297. }
  298. }
  299. }

简单的使用例子:

1、先建好Word文档,设置好排版、插入标签

2、代码如下:

  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3. Report report = new Report();
  4. report.CreateNewDocument(Application.StartupPath + "\\WordDome.doc"); //模板路径
  5. report.InsertValue("date1", "09月04日");//在书签处插入值
  6. report.InsertValue("date2", "09月05日");
  7. report.InsertValue("date3", "09月06日");
  8. report.InsertValue("date4", "09月07日");
  9. report.InsertValue("date5", "09月08日");
  10. report.InsertValue("date6", "09月09日");
  11. report.InsertValue("date7", "09月10日");
  12.  
  13. DataTable dtSource= GetTestDT();
  14.  
  15. int xx = dtSource.Rows.Count;
  16. report.AddRow(, xx);
  17. for (int i = ; i < xx; i++)
  18. {
  19. string[] values = { dtSource.Rows[i]["DEPT_NAME"].ToString(), dtSource.Rows[i]["C1"].ToString(), dtSource.Rows[i]["C2"].ToString(), dtSource.Rows[i]["C3"].ToString(),
  20. dtSource.Rows[i]["C4"].ToString(),dtSource.Rows[i]["C5"].ToString(), dtSource.Rows[i]["C6"].ToString(), dtSource.Rows[i]["C7"].ToString()};
  21. report.InsertCell(, + i, , values); // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
  22. }
  23.        string savename = @"D:\WordDemo" + DateTime.Now.ToString("yyyyMMdd").Trim() + ".doc";//默认名称
  24.        SaveFileDialog saveFileDialog = new SaveFileDialog();
  25.        saveFileDialog.Filter = "doc|*.doc|所有文件|*.*";
  26.        saveFileDialog.FilterIndex = ;
  27.        saveFileDialog.FileName = savename;
  28.        saveFileDialog.RestoreDirectory = true;
  29.        if (saveFileDialog.ShowDialog() == DialogResult.OK)
  30.        {
  31.          savename = saveFileDialog.FileName;//设置保存的路径及文件名
  32.        }
  33.        try
  34.        {
  35.          report.SaveDocument(savename);//保存文件
  36.          MessageBox.Show("保存成功!", "提示");
  37.        }
  38.        catch(Exception ex)
  39.        {
  40.          MessageBox.Show("保存失败:"+ex, "提示");
  41.        }
  42. }

利用标签导出Word文档的更多相关文章

  1. 使用Spire.Doc组件利用模板导出Word文档

    以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权:而且Office安装,包括权限配置也是比较麻烦. 现在流行使用第三方组件来实现对Office的操作, ...

  2. Struts2利用iText导出word文档(包含表格)以提供下载

    J2EE ExcelStrutsXML  在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以word文档形式下载课表.将课表导出到excel里的功能他们已经实现了, ...

  3. 利用NPOI导出Word文档帮助类

    /// <summary> /// NPOI操作Word /// </summary> public class NpoiWordHelper { /// <summar ...

  4. .NET通过调用Office组件导出Word文档

    .NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...

  5. Java 用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  6. 【Java】用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  7. freemarker导出word文档——WordXML格式解析

    前不久,公司一个项目需要实现导出文档的功能,之前是一个同事在做,做了3个星期,终于完成了,但是在项目上线之后却发现导出的文档有问题,此时,这个同事已经离职,我自然成为接班者,要把导出功能实现,但是我看 ...

  8. freemarker导出word文档

    使用freemarker导出word文档的过程 **************************************************************************** ...

  9. 【Java】导出word文档之freemarker导出

    Java导出word文档有很多种方式,本例介绍freemarker导出,根据现有的word模板进行导出 一.简单导出(不含循环导出) 1.新建一个word文件.如下图: 2.使用word将文件另存为x ...

随机推荐

  1. [蓝桥杯2015决赛]四阶幻方(DFS + 剪枝)

    题目描述 把1~16的数字填入4x4的方格中,使得行.列以及两个对角线的和都相等,满足这样的特征时称为:四阶幻方. 四阶幻方可能有很多方案.如果固定左上角为1,请计算一共有多少种方案. 比如: 1  ...

  2. 【剑指Offer面试编程题】题目1511:从尾到头打印链表--九度OJ

    题目描述: 输入一个链表,从尾到头打印链表每个节点的值. 输入: 每个输入文件仅包含一组测试样例. 每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点.第一行是链表第一个节点的值,依次类 ...

  3. 【转载】如何快速转载CSDN中的博客

    前言   对于喜欢逛CSDN的人来说,看别人的博客确实能够对自己有不小的提高,有时候看到特别好的博客想转载下载,但是不能一个字一个字的敲了,这时候我们就想快速转载别人的博客,把别人的博客移到自己的空间 ...

  4. 5G将重新定义物联网和边缘计算

    导读 比上一代蜂窝服务(4G)相比,5G提供的无线蜂窝连接性具有更高的带宽.更低的延迟和更高的设备密度. 比上一代蜂窝服务(4G)相比,5G提供的无线蜂窝连接性具有更高的带宽.更低的延迟和更高的设备密 ...

  5. eclipse不能启动,An internal error occurred during: "reload maven project".

    An internal error occurred during: "reload maven project". 这个错误是因为项目已经关闭,导致 导致此问题的原因是Sprin ...

  6. Day3-A-Problem H. Monster Hunter HDU6326

    Little Q is fighting against scary monsters in the game ``Monster Hunter''. The battlefield consists ...

  7. Codeforces Round #199 (Div. 2) D. Xenia and Dominoes

    把 'O' 看成 'X',然后枚举它的四个方向看看是否能放,然后枚举 $2^4$ 种可能表示每种方向是否放了,放了的话就标成 'X',就相当于容斥,对于新的图去dp. dp就是铺地砖,行用二进制来表示 ...

  8. java校招一些面试的题目

    数组和链表的区别 数组静态分配内存,链表动态分配内存: 数组在内存中连续,链表不一定连续: 数组元素在栈区,链表元素在堆区: 数组利用下标定位,时间复杂度为O(1),链表定位元素时间复杂度O(n) 数 ...

  9. 2.Jsoup

    public static void main(String[] args) { //爬取最大资源网上的数据 //用CSS选择器 try { Document doc = Jsoup.parse(ne ...

  10. NO25 三剑客之SED行天下

    功能说明 Sed是Stream Editor(流编辑器)缩写,是操作.过滤和转换文本内容的强大工具.常用功能有增删改查,过滤,取行. [root@oldboy ~]# sed --version #→ ...