原文地址:http://www.jb51.net/article/55332.htm

 

本文实例讲述了C#实现通过模板自动创建Word文档的方法,是非常实用的技巧。分享给大家供大家参考。具体实现方法如下:

引言:前段时间有项目要用c#生成Word格式的计算报告,通过网络查找到很多内容,但是都很凌乱,于是自己决定将具体的步骤总结整理出来,以便于更好的交流和以后相似问题可以迅速的解决!

现通过具体的示例演示具体的步骤:
第一步,制作模板

1.新建一个文档,设置文档内容。
2.在相应位置插入书签;将鼠标定位到要插入书签的位置,点击“插入”>“书签”,弹出对话框,输入书签名,点击“添加”按钮。
3.保存模板,命名为“模板1.dot”或者“模板1.doc”

第二步,设置项目中的引用

1.右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2.在“添加引用”对话框中,选择“COM”>“Microsoft Word 11.0 Object Library”,点击“确定”按钮
3.相同操作打开“添加引用”对话框中,选择“浏览”项,查找到”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”按钮
注意:此处要查找的“Microsoft.Office.Interop.Word.dll”版本必须为“11.*.*.*”,“*”代表数字

第三步,编码

这一步分成两个部分
第一部分,Report类的编码
这部分我已经封装好,为文件“Report.cs”,可以直接使用

具体实现代码如下:(代码中有比较详细的注释)

 

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.Office.Interop.Word;

namespace MYNAMESPACE //这边需要换成自己的命名空间名

{

classReport

{

private_ApplicationwordApp= null;

private_DocumentwordDoc= null;

public_ApplicationApplication

{

get

{

return wordApp;

}

set

{

wordApp = value;

}

}

public_DocumentDocument

{

get

{

return wordDoc;

}

set

{

wordDoc = value;

}

}

//通过模板创建新文档

publicvoidCreateNewDocument(stringfilePath)

{

killWinWordProcess();

wordApp= new ApplicationClass();

wordApp.DisplayAlerts =WdAlertLevel.wdAlertsNone;

wordApp.Visible =false;

objectmissing =System.Reflection.Missing.Value;

objecttemplateName =filePath;

wordDoc= wordApp.Documents.Open(reftemplateName, refmissing,

ref missing, ref missing,ref missing, ref missing, refmissing,

ref missing, ref missing,ref missing, ref missing, refmissing,

ref missing, ref missing,ref missing, ref missing);

}

//保存新文件

publicvoidSaveDocument(stringfilePath)

{

objectfileName =filePath;

objectformat =WdSaveFormat.wdFormatDocument;//保存格式

objectmiss =System.Reflection.Missing.Value;

wordDoc.SaveAs(reffileName, 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对象

objectSaveChanges =WdSaveOptions.wdSaveChanges;

objectOriginalFormat =WdOriginalFormat.wdOriginalDocumentFormat;

objectRouteDocument =false;

wordDoc.Close(refSaveChanges, refOriginalFormat, refRouteDocument);

wordApp.Quit(refSaveChanges, refOriginalFormat, refRouteDocument);

}

//在书签处插入值

publicboolInsertValue(stringbookmark, stringvalue)

{

objectbkObj =bookmark;

if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark))

{

wordApp.ActiveDocument.Bookmarks.get_Item(refbkObj).Select();

wordApp.Selection.TypeText(value);

return true;

}

returnfalse;

}

//插入表格,bookmark书签

publicTableInsertTable(stringbookmark, int rows, int columns,float width)

{

objectmiss =System.Reflection.Missing.Value;

objectoStart =bookmark;

Rangerange =wordDoc.Bookmarks.get_Item(refoStart).Range;//表格插入位置

TablenewTable =wordDoc.Tables.Add(range,rows, columns, ref miss, refmiss);

//设置表的格式

newTable.Borders.Enable =1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)

newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//边框宽度

if(width != 0)

{

newTable.PreferredWidth=width;//表格宽度

}

newTable.AllowPageBreaks =false;

returnnewTable;

}

//合并单元格 表名,开始行号,开始列号,结束行号,结束列号

publicvoidMergeCell(Microsoft.Office.Interop.Word.Tabletable, int row1, int column1,int row2, int column2)

{

table.Cell(row1,column1).Merge(table.Cell(row2,column2));

}

//设置表格内容对齐方式Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)

publicvoidSetParagraph_Table(Microsoft.Office.Interop.Word.Tabletable, int Align, int Vertical)

{

switch(Align)

{

case -1:table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;break;//左对齐

case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;//水平居中

case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;//右对齐

}

switch(Vertical)

{

case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;//顶端对齐

case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;//垂直居中

case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;//底端对齐

}

}

//设置表格字体

publicvoidSetFont_Table(Microsoft.Office.Interop.Word.Tabletable, string fontName, double size)

{

if(size != 0)

{

table.Range.Font.Size =Convert.ToSingle(size);

}

if(fontName !="")

{

table.Range.Font.Name =fontName;

}

}

//是否使用边框,n表格的序号,use是或否

publicvoidUseBorder(int n,bool use)

{

if(use)

{

wordDoc.Content.Tables[n].Borders.Enable =1; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)

}

else

{

wordDoc.Content.Tables[n].Borders.Enable =2; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)

}

}

//给表格插入一行,n表格的序号从1开始记

publicvoidAddRow(int n)

{

objectmiss =System.Reflection.Missing.Value;

wordDoc.Content.Tables[n].Rows.Add(refmiss);

}

//给表格添加一行

publicvoidAddRow(Microsoft.Office.Interop.Word.Tabletable)

{

objectmiss =System.Reflection.Missing.Value;

table.Rows.Add(refmiss);

}

//给表格插入rows行,n为表格的序号

publicvoidAddRow(int n, int rows)

{

objectmiss =System.Reflection.Missing.Value;

Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];

for(inti = 0; i < rows; i++)

{

table.Rows.Add(refmiss);

}

}

//给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素

publicvoidInsertCell(Microsoft.Office.Interop.Word.Tabletable, int row, int column,string value)

{

table.Cell(row,column).Range.Text =value;

}

//给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素

publicvoidInsertCell(int n, int row,int column, string value)

{

wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value;

}

//给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值

publicvoidInsertCell(int n, int row,int columns, string[] values)

{

Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];

for(inti = 0; i < columns; i++)

{

table.Cell(row,i + 1).Range.Text =values[i];

}

}

//插入图片

publicvoidInsertPicture(stringbookmark, stringpicturePath, floatwidth, float hight)

{

object miss = System.Reflection.Missing.Value;

objectoStart =bookmark;

ObjectlinkToFile =false;    //图片是否为外部链接

ObjectsaveWithDocument =true; //图片是否随文档一起保存

objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;//图片插入位置

wordDoc.InlineShapes.AddPicture(picturePath,ref linkToFile, ref saveWithDocument, refrange);

wordDoc.Application.ActiveDocument.InlineShapes[1].Width=width; //设置图片宽度

wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; //设置图片高度

}

//插入一段文字,text为文字内容

publicvoidInsertText(stringbookmark, stringtext)

{

objectoStart =bookmark;

objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;

Paragraphwp =wordDoc.Content.Paragraphs.Add(refrange);

wp.Format.SpaceBefore= 6;

wp.Range.Text =text;

wp.Format.SpaceAfter =24;

wp.Range.InsertParagraphAfter();

wordDoc.Paragraphs.Last.Range.Text ="\n";

}

//杀掉winword.exe进程

publicvoidkillWinWordProcess()

{

System.Diagnostics.Process[]processes=System.Diagnostics.Process.GetProcessesByName("WINWORD");

foreach (System.Diagnostics.Processprocess in processes)

{

bool b = process.MainWindowTitle=="";

if (process.MainWindowTitle =="")

{

process.Kill();

}

}

}

}

}

第二部分,具体生成文档的编码

代码见下文:
1.首先需要载入模板
Report report =new Report();
report.CreateNewDocument(TemPath); //模板路径
2.插入一个值
report.InsertValue("Bookmark_value","世界杯");//在书签“Bookmark_value”处插入值
3.创建一个表格
Table table =report.InsertTable("Bookmark_table", 2, 3, 0); //在书签“Bookmark_table”处插入2行3列行宽最大的表
4.合并单元格
report.MergeCell(table, 1, 1, 1, 3); //表名,开始行号,开始列号,结束行号,结束列号
5.表格添加一行
report.AddRow(table); //表名
6.在单元格中插入值
report.InsertCell(table, 2, 1,"R2C1");//表名,行号,列号,值
7.设置表格中文字的对齐方式
report.SetParagraph_Table(table, -1, 0);//水平方向左对齐,垂直方向居中对齐
8.设置表格字体
report.SetFont_Table(table,"宋体", 9);//宋体9磅
9.给现有的表格添加一行
report.AddRow(1);//给模板中第一个表格添加一行
10.确定现有的表格是否使用边框
report.UseBorder(1,true); //模板中第一个表格使用实线边框
11.给现有的表格添加多行
report.AddRow(1, 2);//给模板中第一个表格插入2行
12.给现有的表格插入一行数据
string[] values={"英超", "意甲", "德甲","西甲", "法甲" };
report.InsertCell(1, 2, 5,values); //给模板中第一个表格的第二行的5列分别插入数据
13.插入图片
string picturePath = @"C:\Documents and Settings\Administrator\桌面\1.jpg";
report.InsertPicture("Bookmark_picture",picturePath, 150, 150); //书签位置,图片路径,图片宽度,图片高度
14.插入一段文字
string text = "长期从事电脑操作者,应多吃一些新鲜的蔬菜和水果,同时增加维生素A、B1、C、E的摄入。为预防角膜干燥、眼干涩、视力下降、甚至出现夜盲等,电 脑操作者应多吃富含维生素A的食物,如豆制品、鱼、牛奶、核桃、青菜、大白菜、空心菜、西红柿及新鲜水果等。";
report.InsertText("Bookmark_text",text);
15.最后保存文档
report.SaveDocument(RepPath); //文档路径
第四步,运行程序生成文档,并查看生成的文档

希望本文所述对大家的C#程序设计有所帮助。

C#实现通过模板自动创建Word文档的方法的更多相关文章

  1. C#程序通过模板自动创建Word文档

    引言:前段时间有项目要用c#生成Word格式的计算报告,通过网络查找到很多内容,但是都很凌乱,于是自己决定将具体的步骤总结整理出来,以便于更好的交流和以后相似问题可以迅速的解决! 现通过具体的示例演示 ...

  2. [java,2017-05-04] 创建word文档

    package test; import java.text.SimpleDateFormat; import java.util.Date; import com.aspose.words.Data ...

  3. 在C#中创建word文档

    在下面文档中  首先引用word组件:Microsoft.Office.Interop.Word 在头文件中写上 using Word = Microsoft.Office.Interop.Word; ...

  4. velocity模板技术生成word文档

    本文介绍採用velocity技术在Java中生成word文档的方法. 1.新建一个word文档,编辑内容例如以下: 2.将上述word文档另存为htm格式的文件 3.新建一个Java Project项 ...

  5. Java 后台创建word 文档

    ---恢复内容开始--- Java 后台创建 word 文档 自己总结  网上查阅的文档 分享POI 教程地址:http://www.tuicool.com/articles/emqaEf6 方式一. ...

  6. OpenXml SDK 2.0 创建Word文档 添加页、段落、页眉和页脚

    using (WordprocessingDocument objWordDocument = WordprocessingDocument.Create(@"C:\********.doc ...

  7. 自动创建xml文档

    自动创建xml文档 import xml.etree.ElementTree as ET print(dir(ET)) #ET里面有Element方法 root = ET.Element(" ...

  8. Python批量创建word文档(2)- 加图片和表格

    Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.要求在文档开始处给出banner条,价格日期等用表格表示.最后贴上自己的联系 ...

  9. Python批量创建word文档(1)- 纯文字

    Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.最后贴上自己的联系方式.代码如下: 1 ''' 2 #python根据需求新 ...

随机推荐

  1. php大力力 [012节]PHP连接mySQL数据库

    php大力力 [012节]PHP连接mySQL数据库 1.用简单的php测试代码,而不是直接进入前端页面,越简单越好 2.在=号前后,不要写空格,万一写了中文空格,排除错误很麻烦. 3.我在mysql ...

  2. 第一个PHP程序

    <html> <head> <title><?php echo"这是第一个php程序"?></title> <st ...

  3. WPF Step By Step 自定义模板

    WPF Step By Step 自定义模板 回顾 上一篇,我们简单介绍了几个基本的控件,本节我们将讲解每个控件的样式的自定义和数据模板的自定义,我们会结合项目中的具体的要求和场景来分析,给出我们实现 ...

  4. magento转移服务器和magento建立多站点总结

    magento转移服务器和magento建立多站点总结第一. 我们首先要做的就是把服务器上的magento转移到本地上来.详细步骤:1. 直接用magento的备份系统把网上数据库备份.如图:2. 数 ...

  5. magnetom模板制作

    我个人认为Magento模板制作的难点在于不了解Magento的架构,不会调动block.Magento的block调动几乎都是靠xml.在下面的内容会提及如何操作. 制作Magento模板的前提是: ...

  6. 让UIWebView弹出键盘上的按钮显示中文

    UIWebView是一个很常用的视图,一般用来加载网页,比如百度: 点击文本框输入框后,会弹出一个带有toolbar的键盘,toolbar中有3个辅助按钮 有了这3个按钮,是方便很多,但默认是英文的, ...

  7. Windows上的文件合并命令

    从Linux转到Windowns后,发现很多好用的shell命令都没有了,但实际情况是Windows一样有DOS时代的命令窗口,在CLI年代用DOS的人也要干活. 比如,今天想将几个单独的sql文件整 ...

  8. Xcode 工程文件打开不出来, cannot be opened because the project file cannot be parsed.

    svn更新代码后,打开xcode工程文件,会出现  xxx..xcodeproj  cannot be opened because the project file cannot be parsed ...

  9. Java-->实现群聊功能(C/S模式--TCP协议)

    --> Java 对TCP协议的支持: --> java.net包中定义了两个类ServerSocket 和Socket ,分别用来实现双向连接的server 端和client 端. -- ...

  10. ZOJ 3804--解题报告

    题目相关: 3804相关链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5336 宠物(minion)在N*M的矩形玩游戏 ...