C#操作Word2010实现

概述

某项目需要自动生成Word文档,查找了许多资料,发现还是C#实现起来比较容易,也比较灵活。

环境:
Office 2010
Visual Studio 2010
Win10

网上找了很多教程,首先需要设置引用。
1.右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2.在“添加引用”对话框中,选择“COM”>“Microsoft Word 15.0 Object Library”,点击“确定”按钮(这个版本号和本机安装的Word版本有关,2010是15.0)
3.相同操作打开“添加引用”对话框中,选择“浏览”项,查找到”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”按钮。

整个类的代码如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;

namespace DocCreator
{
    class CreateDoc
    {
        private Microsoft.Office.Interop.Word.Application wordApp = null;
        private Document wordDoc = null;

        public Application Application
        {
            get
            {
                return wordApp;
            }

            set
            {
                wordApp = value;
            }
        }

        public Document Document
        {
            get
            {
                return wordDoc;
            }

            set
            {
                wordDoc= value;
            }
        }

        //通过模板创建新文档
        public void CreateNewDocument(string filePath)
        {
            killWinWordProcess();
            wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            wordApp.Visible =false;
            object missing = System.Reflection.Missing.Value;
            object templateName = filePath;
            wordDoc = wordApp.Documents.Open(ref templateName,ref missing,
                ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,
                ref missing,ref missing,ref missing,ref missing,ref missing);
        }

        //保存新文件
        public void SaveDocument(string filePath)
        {
            object fileName = filePath;
            obj
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值