欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

C#操作word文档_替换_生成word_.NET使用模板生成文档_C#文件下载

程序员文章站 2022-02-02 20:31:25
...

我以前在项目中曾有这样的需求、通过已经存在的 word 模板来生成新的 word 文档

虽然到目前为止、离我当初使用也有一段时间了、但是我还是觉得有必要把这种方法记录下来

说不定以后还用得到、同时也可以帮助一些和我有相同需求的朋友、话不多说

如果想使用 word 模板生成新的 word 文档的话有两种方式


一、通过宏生成(个人觉得比较麻烦)

这种方式我这里不做说明、有兴趣的朋友可自己去找一下方式


二、使用固定文字替换的方式(也就是我使用的方式)

1、引用 word 的dll

C#操作word文档_替换_生成word_.NET使用模板生成文档_C#文件下载


2、打开项目里面预先准备好的模板文档、以及把样式设置好

代码入下

//打开文档:
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application oWord;
Microsoft.Office.Interop.Word._Document oDoc;
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = true;
object fileName = “文档路径";
//如:object fileName = @"C:	est.doc";
oDoc = oWord.Documents.Open(ref fileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

object FindText, ReplaceWith, Replace;//
object MissingValue = Type.Missing;


3、找到 word 里面预先设置好准备替换的字符进行替换

代码如下

//word 模板预先设置要替换的字符
oDoc.Content.Find.Text = "[test]";
//要查找的文本
FindText = "[test]";
//替换文本
ReplaceWith = "替换的字符";
Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
//移除Find的搜索文本和段落格式设置
oDoc.Content.Find.ClearFormatting();
if (oDoc.Content.Find.Execute(ref FindText, ref MissingValue,
	ref MissingValue, ref MissingValue, ref MissingValue, 
	ref MissingValue, ref MissingValue, ref MissingValue, 
	ref MissingValue, ref ReplaceWith, ref Replace, 
	ref MissingValue, ref MissingValue, ref MissingValue, 
	ref MissingValue)) { }


4、替换完成之后还得把打开的文档关闭、然后退出 word 程序

代码如下

savePath = "新文件保存路径";
//如:savePath = @"C:
ewtest.doc";
oDoc.SaveAs(savePath);
oDoc.Close();
oWord.Quit();


5、让用户下载已经生成的新文件(web项目)

代码如下

try
{
	System.IO.FileStream fs = new System.IO
		.FileStream("刚刚保存的路径", 
		System.IO.FileMode.Open);
	byte[] bytes = new byte[(int)fs.Length];
	fs.Read(bytes, 0, bytes.Length);
	fs.Close();
	Response.Charset = "UTF-8";
	Response.ContentEncoding = System.Text.Encoding
		.GetEncoding("UTF-8");
	Response.ContentType = "application/octet-stream";

	Response.AddHeader("Content-Disposition", 
		"attachment; filename=test.doc");
	Response.BinaryWrite(bytes);
	Response.Flush();
	Response.End();
}
catch (Exception)
{
	Response.Write("你访问的资源不存在!");
	return new EmptyResult();
}