2012-03-10 12:13:49|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:C#, Office套件|来源:唯设编程网
/// <summary> /// 插入表格 /// </summary> /// <param name="boookmark">书签</param> /// <param name="rows"></param> /// <param name="columns"></param> /// <param name="width"></param> /// <returns></returns> public Table InsertTable(string bookmark, int rows, int columns, float width) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range; //表格插入位置 Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss); //设置表的格式,允许有边框,默认没有边框(为0时报错, //1为实线边框,2、3为虚线边框,以后的数字没有试过) newTable.Borders.Enable = 1; newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框的宽度 if (width != 0) { //表格的宽度 newTable.PreferredWidth = width; } newTable.AllowPageBreaks = false; return newTable; }
/// <summary> /// 插入图片 /// </summary> /// <param name="bookmark"></param> /// <param name="picturePath"></param> /// <param name="width"></param> /// <param name="height"></param> public void InsertPicture(string bookmark, string picturePath, float width, float height) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; object linkToFile = false; //图片是否为外部链接 object saveWidthDocument = true; //图片是否随文档一起保存 object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片的插入位置 wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWidthDocument, ref range); if (width != 0) { //设置图片宽度 wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; } if (height != 0) { //设置图片高度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = height; } }
/// <summary> /// 插入一段文字 /// </summary> /// <param name="bookmark">书签</param> /// <param name="text">文字内容</param> public void InsertText(string bookmark, string text) { object oStart = bookmark; object range = wordDoc.Bookmarks.get_Item(ref oStart).Range; Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range); wp.Format.SpaceBefore = 6; wp.Range.Text = text; wp.Format.SpaceAfter = 24; wp.Range.InsertParagraphAfter(); wordDoc.Paragraphs.Last.Range.Text = " "; }
/// <summary> /// 杀掉窗体标题为空的winword.exe进程 /// </summary> public void killWinWordProcess() { Process[] processes = Process.GetProcessesByName("WINWORD"); foreach (Process process in process) { if (process.MainWindowTitle == "") { process.Kill(); } } }
关于C#在Windows环境对进程进行的操作,在C#使用Process类的Kill和CloseMainWindow方法结束进程中有详细的介绍,有感兴趣的读者可以查阅。
本文在文章Win7环境C#使用Word模板生成报告(一)的基础上进行了补充,通过这两篇文章的介绍,读者已经可以完成C#使用Word模板自动化生成报告的工作了。由于水平和经验不够,本文涉及到的都是一些简单的基础操作,不足之处希望大家一起讨论。