C# word 操作进阶-01-模板环境[转载]

原文:https://www.cnblogs.com/oBehavior/p/16528897.html
个人转载,并根据我的情况修改。
C# word 操作进阶-01-模板环境

首先,你的计算机上必须安装 Microsoft Office Excel 2007 和 Microsoft Office Word 2007 或更高版本。

我这里项目直接com引用了office,大家可根据情况引用。
在这里插入图片描述

引用组件后,就可以新建word帮助类了(WordHelper.cs)

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using DataTable = System.Data.DataTable;
using word = Microsoft.Office.Interop.Word;

namespace Hsware.Util
{
    /// <summary>
    /// 生成word帮助类
    /// 2022年7月26日13:35:04
    /// </summary>
    public class WordHelper
    {
        #region 基础区
        private object tempfile = null;//模板绝对地址
        private object savefile = null;//保存文件绝对地址
        private static Document wdoc = null; //word文档
        private static Application wapp = null; //word进程
        private object missing = System.Reflection.Missing.Value;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="tempfile">模板绝对地址</param>
        /// <param name="savefile">保存文件绝对地址</param>
        public WordHelper(string tempfile, string savefile)
        {
            this.tempfile = @tempfile;
            this.savefile = @savefile;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        private TData Init()
        {
            TData<string> obj = new TData<string>();
            if (!File.Exists(tempfile.ToString()))
            {
                obj.Message = $"{tempfile}模板文件不存在,请先设置模板文件。";
                return obj;
            }
            wapp = new Application();
            wapp.Visible = false;
            wdoc = wapp.Documents.Add(ref tempfile, ref missing, ref missing, ref missing);
            wdoc.Activate();// 当前文档置前
            obj.Tag = 1;
            return obj;
        }

        /// <summary>
        /// 给指定table按照字典赋值
        /// 应用场景:word中table是重复的利用,可以选择复制table,并调用此方法赋值
        /// </summary>
        /// <param name="table"></param>
        /// <param name="dc"></param>
        /// <returns></returns>
        private bool ReplaceTableRang(word.Table table, Dictionary<string, string> dc)
        {
            try
            {
                object replacearea = word.WdReplace.wdReplaceAll;

                foreach (string item in dc.Keys)
                {
                    object replacekey = item;
                    object replacevalue = dc[item];
                    table.Range.Find.Execute(ref replacekey, ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing, ref missing, ref missing,
                     ref replacevalue, ref replacearea, ref missing, ref missing, ref missing,
                     ref missing);
                }
                return true;
            }
            catch (Exception ex)
            {
                DisposeWord();
                //messagebox.show(string.format("{0}模板中没有找到指定的要替换的表达式。{1}", tempfile, ex.message));
                return false;
            }
        }

        /// <summary>
        /// 加载字典参数
        /// </summary>
        /// <param name="dc"></param>
        /// <returns></returns>
        private TData ReplaceAllRang(Dictionary<string, string> dc)
        {
            TData<string> obj = new TData<string>();
            try
            {
                object replacearea = word.WdReplace.wdReplaceAll;

                foreach (string item in dc.Keys)
                {
                    object replacekey = item;
                    object replacevalue = dc[item];
                    wapp.Selection.Find.Execute(ref replacekey, ref missing, ref missing, ref missing,
                     ref missing, ref missing, ref missing, ref missing, ref missing,
                     ref replacevalue, ref replacearea, ref missing, ref missing, ref missing,
                     ref missing);
                }
                obj.Tag = 1;
            }
            catch (Exception ex)
            {
                obj.Message = $"{tempfile}模板中没有找到指定的要替换的表达式。{ex.Message}";
            }
            return obj;
        }

        private void DisposeWord()
        {
            object saveoption = word.WdSaveOptions.wdSaveChanges;

            wdoc.Close(ref saveoption, ref missing, ref missing);

            saveoption = word.WdSaveOptions.wdDoNotSaveChanges;

            wapp.Quit(ref saveoption, ref missing, ref missing); //关闭word进程
        }
        #endregion

    }
}

其中TData类仅仅是消息类,可自定义返回值或者类,个人习惯,不过我喜欢带消息的操作结果,不喜欢bool。

    /// <summary>
    /// 数据传输对象
    /// </summary>
    public class TData
    {
        /// <summary>
        /// 操作结果,Tag为1代表成功,(默认值)0代表失败,其他的验证返回结果,可根据需要设置
        /// </summary>
        public int Tag { get; set; } = 0;

        /// <summary>
        /// 提示信息或异常信息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 扩展Message
        /// </summary>
        public string Description { get; set; }
    }

我根据个人需求,修改原文的代码:

    /// <summary>
    /// 数据传输对象
    /// </summary>
    public class TData
    {
        /// <summary>
        /// 操作结果,1代表成功,(默认值)0代表失败,其他的验证返回结果,可根据需要设置
        /// </summary>
        public int State{ get; set; } = 0;

        /// <summary>
        /// 提示信息或异常信息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 扩展Message
        /// 例如Dictionary[0x2034]="文件不存在。",字典信息在数据库中预定。
        /// </summary>
        public Dictionary<int, string> Description { get; set; }
    }

到了这一步,要先保证代码没有错误。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值