资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C#如何根据Word模版生成Word文件-创新互联

这篇文章给大家分享的是有关C#如何根据Word模版生成Word文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名、网络空间、营销软件、网站建设、岳阳网站维护、网站推广。

具体内容如下

1、指定的word模版

C#如何根据Word模版生成Word文件

2、生成word类

添加com Microsoft word 11.0 Object Library 引用

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
 
namespace Headfree.DefUI
{
  public class WordUtility
  {
    private object tempFile = null;
    private object saveFile = null;
    private static Word._Document wDoc = null; //word文档
    private static Word._Application wApp = null; //word进程
    private object missing = System.Reflection.Missing.Value;
 
    public WordUtility(string tempFile, string saveFile)
    {
      this.tempFile = Path.Combine(Application.StartupPath, @tempFile);
      this.saveFile = Path.Combine(Application.StartupPath, @saveFile);
    }
 
    /// 
    /// 模版包含头部信息和表格,表格重复使用
    /// 
    /// 重复表格的数据
    /// word中要替换的表达式和表格字段的对应关系
    /// 简单的非重复型数据
    public bool GenerateWord(DataTable dt, Dictionary expPairColumn, Dictionary simpleExpPairValue)
    {
      if (!File.Exists(tempFile.ToString()))
      {
        MessageBox.Show(string.Format("{0}模版文件不存在,请先设置模版文件。", tempFile.ToString()));
        return false;
      }
      try
      {
        wApp = new Word.Application();
 
        wApp.Visible = false;
 
        wDoc = wApp.Documents.Add(ref tempFile, ref missing, ref missing, ref missing);
 
        wDoc.Activate();// 当前文档置前
 
        bool isGenerate = false;
 
        if (simpleExpPairValue != null && simpleExpPairValue.Count > 0)
          isGenerate = ReplaceAllRang(simpleExpPairValue);
 
        // 表格有重复
        if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0)
          isGenerate = GenerateTable(dt, expPairColumn);
 
        if (isGenerate)
          wDoc.SaveAs(ref saveFile, 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, ref missing);
 
        DisposeWord();
 
        return true;
      }
      catch (Exception ex)
      {
        MessageBox.Show("生成失败" + ex.Message);
        return false;
      }
    }
 
    /// 
    /// 单个替换 模版没有重复使用的表格
    /// 
    /// 要替换的
    public bool GenerateWord(Dictionary dc)
    {
      return GenerateWord(null, null, dc);
    }
 
 
    private bool GenerateTable(DataTable dt, Dictionary expPairColumn)
    {
      try
      {
        int tableNums = dt.Rows.Count;
 
        Word.Table tb = wDoc.Tables[1];
 
        tb.Range.Copy();
 
        Dictionary dc = new Dictionary();
        for (int i = 0; i < tableNums; i++)
        {
          dc.Clear();
 
          if (i == 0)
          {
            foreach (string key in expPairColumn.Keys)
            {
              string column = expPairColumn[key];
              object value = null;
              value = dt.Rows[i][column];
              dc.Add(key, value);
            }
 
            ReplaceTableRang(wDoc.Tables[1], dc);
            continue;
          }
 
          wDoc.Paragraphs.Last.Range.Paste();
 
          foreach (string key in expPairColumn.Keys)
          {
            string column = expPairColumn[key];
            object value = null;
            value = dt.Rows[i][column];
            dc.Add(key, value);
          }
 
          ReplaceTableRang(wDoc.Tables[1], dc);
        }
 
 
        return true;
      }
      catch (Exception ex)
      {
        DisposeWord();
        MessageBox.Show("生成模版里的表格失败。" + ex.Message);
        return false;
      }
    }
 
    private bool ReplaceTableRang(Word.Table table, Dictionary 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;
      }
    }
 
    private bool ReplaceAllRang(Dictionary dc)
    {
      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);
        }
        return true;
      }
      catch (Exception ex)
      {
        MessageBox.Show(string.Format("{0}模版中没有找到指定的要替换的表达式。{1}", tempFile, ex.Message));
        return false;
      }
    }
 
    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进程
    }
  }
}

3、效果

C#如何根据Word模版生成Word文件

感谢各位的阅读!关于“C#如何根据Word模版生成Word文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页名称:C#如何根据Word模版生成Word文件-创新互联
文章出自:http://cdkjz.cn/article/ddgicc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220