C#使用Microsoft.Office.Interop.Word生成word文档报告的2种方式

1:使用Microsoft.Office.Interop.Word进行编辑,进行内容的填写
2:使用Microsoft.Office.Interop.Word读取word模版,对模版中标签内容进行填写。
方法1:
在项目中导入Microsoft.Office.Interop.Word包,具体方法详情参考Microsoft官网。
可直接生成测试模块,进行测试~

using System;
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;

namespace ColumnHoleApp.Tools
{
   /// <summary>
   /// 用于生成word文件
   /// </summary>
    public class FileOperator
    {
        public void CreateDoc()
        {
            Object path = Environment.CurrentDirectory + "\\test.doc";
            var wordApp = new Word.Application
            {
                Visible = true
            };
            object unite = Word.WdUnits.wdStory;
            Word.Document wordDoc = wordApp.Documents.Add();
            wordDoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4;
            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 18;
            wordDoc.Paragraphs.Last.Range.Text = "质量报告\n";
            wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾


            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 12;
            wordDoc.Paragraphs.Last.Range.Text = "工程名称:\n";
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 10;
            wordDoc.Paragraphs.Last.Range.Text = "井深度/米:";
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            wordDoc.Paragraphs.Last.Range.InsertAfter("                          ");//加入空格

            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 10;
            wordDoc.Paragraphs.Last.Range.InsertAfter("倾斜度/百分比:\n");
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 10;
            wordDoc.Paragraphs.Last.Range.Text = "泥厚深度/米:";
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            wordDoc.Paragraphs.Last.Range.InsertAfter("                          ");//加入空格

            wordApp.Selection.EndKey(ref unite);//将光标移到文本末尾
            wordDoc.Paragraphs.Last.Range.Font.Size = 10;
            wordDoc.Paragraphs.Last.Range.InsertAfter("孔径/米:\n");
            wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

            wordDoc.Shapes.AddLine(80, 100, 520, 100);//在指定位置画横线

            //WdSaveFormat为Word 2003文档的保存格式
            object format = Word.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault
                                                               //将wordDoc文档对象的内容保存为DOCX文档
            wordDoc.SaveAs(ref path, ref format);
            wordDoc.Close();
            //关闭wordApp组件对象
            wordApp.Quit();
        }
    }
}

生成word文件样式如下:
在这里插入图片描述方法2:根据word模版进行数据填充
模版样式如下:在这里插入图片描述在模版中定义相关位置的书签,书签与填充值在代码中保存为Map对象,是key-value关系。
代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Word = Microsoft.Office.Interop.Word;
namespace ColumnHoleApp.Tools
{
    /// <summary>
    /// 根据word模版来生成报告
    /// </summary>
    public class AccordingTemplentPdf
    {
        public void CreateReportPdf()
        {
            string path = @"E:\testtemp.dotx";
            SetValue(path, @"E:\testTemplete2019111.doc");
        }
        /// <summary>
        /// 给书签内容填充数据,并调用生成word方法生成word报告
        /// </summary>
        /// <param name="urlstring">模板文件</param>
        /// <param name="fileName">新文件</param>
        public bool SetValue(string urlstring, string fileName)
        {
            bool result = false;
            try
            {
                string project = "测试工程1";
                string value1 = "11.11";
                string value2 = "22.22";
                string value3 = "33.33";
                string value4 = "44.44";
                #region 声明参数
                Dictionary<string, string> DList = new Dictionary<string, string>
                {
                    { "project", project },
                    { "value1", value1 },
                    { "value2", value2 },
                    { "value3", value3 },
                    { "value4", value4 }
                };
                #endregion
                if (CreateWord(urlstring, fileName, DList))
                {
                    result = true;
                }
            }
            catch
            {
                return false;
            }
            return result;
        }
        /// <summary>
        /// 生成word
        /// </summary>
        /// <param name="templateFile"></param>
        /// <param name="fileName"></param>
        /// <param name="myDictionary"></param>
        /// <returns></returns>
        public static bool CreateWord(string templateFile, string fileName, Dictionary<string, string> myDictionary)
        {
            try
            {
                //生成word程序对象
                Word.Application app = new Word.Application();
                //模板文件
                string TemplateFile = templateFile;
                //模板文件拷贝到新文件
                File.Copy(TemplateFile, fileName);
                //生成documnet对象
                Word._Document doc = new Word.Document();
                object Obj_FileName = fileName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;
                //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                doc.Activate();
                #region 声明参数
                if (myDictionary.Count > 0)
                {
                    object what = Word.WdGoToItem.wdGoToBookmark;
                    object WordMarkName;
                    foreach (var item in myDictionary)
                    {
                        WordMarkName = item.Key;
                        doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置
                        doc.ActiveWindow.Selection.TypeText(item.Value);//插入的内容,插入位置是word模板中书签定位的位置
                        //doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式
                    }
                }
                #endregion
                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);
                return true;
            }
            catch
            {

                return false;
            }
        }
}
}

方法2更直观便捷

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页