个人资料

主页 博客 留言板 搜索
跳过导航链接首页 > 博客列表 > 博客正文

C#操作word

分类

1 根据模板创建word

string dir = System.Web.HttpContext.Current.Server.MapPath("");
//首先在类库添加using System.web的引用
if (!Directory.Exists(dir + "//file")) 
{
	Directory.CreateDirectory(dir + "//file");
	? //创建文件所在目录
}
string name = DateTime.Now.ToLongDateString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".doc";
// + DateTime.Now.Second.ToString() 
object filename = dir + "//file//" + name;
? //文件保存路径
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Microsoft.Office.Interop.Word.Application();
//debug
WordApp.Visible = false;
object oTemplate = dir + @".\内部设计文件格式模板.dot";
Microsoft.Office.Interop.Word._Document WordDoc= WordApp.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

2 光标跳转到模板中的书签位置

//-------------------------------------------前往内容开始的书签
object what = WdGoToItem.wdGoToBookmark;
//object which = WdGoToDirection.wdGoToAbsolute;
object bookmarkname = "ContentStartPoint";
WordApp.Selection.GoTo(what, oMissing, oMissing, bookmarkname);

3 写入文本并指定样式

WordApp.Selection.TypeText("1 " + title1.Value);
WordApp.Selection.set_Style("标题 1");
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeText(testcontent1.Value);
WordApp.Selection.set_Style("正文2");
WordApp.Selection.TypeParagraph();

4 生成自动目录

object oTrue = true;
object UpHeadingLevel = 1;
object LowHeadingLevel = 3;
object Style1 = Word.WdBuiltinStyle.wdStyleHeading1;
WordDoc.TablesOfContents.Add(WordApp.Selection.Range,
                ref Style1, ref UpHeadingLevel, ref LowHeadingLevel,    
                ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                ref oMissing, ref oTrue, ref oMissing, ref oMissing);


5 保存word至指定路径并退出word程序

WordDoc.SaveAs(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);
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//关闭word
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
ResultLink.HRef = "./file//" + name;



songshizhao
最初发表2017/10/27 1:12:21 最近更新2017/10/27 1:12:21 883
为此篇作品打分
10