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

 更新时间:2017年10月27日 16:27:29   作者:大西瓜3721  
这篇文章主要为大家详细介绍了C#根据Word模版生成Word文件的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C#根据Word模版生成Word文的具体代码,供大家参考,具体内容如下

1、指定的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);
    }
 
    /// <summary>
    /// 模版包含头部信息和表格,表格重复使用
    /// </summary>
    /// <param name="dt">重复表格的数据</param>
    /// <param name="expPairColumn">word中要替换的表达式和表格字段的对应关系</param>
    /// <param name="simpleExpPairValue">简单的非重复型数据</param>
    public bool GenerateWord(DataTable dt, Dictionary<string, string> expPairColumn, Dictionary<string, string> 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;
      }
    }
 
    /// <summary>
    /// 单个替换 模版没有重复使用的表格
    /// </summary>
    /// <param name="dc">要替换的</param>
    public bool GenerateWord(Dictionary<string, string> dc)
    {
      return GenerateWord(null, null, dc);
    }
 
 
    private bool GenerateTable(DataTable dt, Dictionary<string, string> expPairColumn)
    {
      try
      {
        int tableNums = dt.Rows.Count;
 
        Word.Table tb = wDoc.Tables[1];
 
        tb.Range.Copy();
 
        Dictionary<string, object> dc = new Dictionary<string, object>();
        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<string, object> 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<string, string> 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# WPF中CheckBox样式的使用总结

    c# WPF中CheckBox样式的使用总结

    这篇文章主要介绍了c# WPF中CheckBox样式的使用总结,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-03-03
  • C#使用反射机制实现延迟绑定

    C#使用反射机制实现延迟绑定

    这篇文章介绍了C#使用反射实现延迟绑定的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-07-07
  • C#面向对象实现图书管理系统

    C#面向对象实现图书管理系统

    这篇文章主要为大家详细介绍了C#面向对象实现图书管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C#获取指定文件著作权信息的方法

    C#获取指定文件著作权信息的方法

    这篇文章主要介绍了C#获取指定文件著作权信息的方法,涉及C#中FileVersionInfo类的使用技巧,需要的朋友可以参考下
    2015-04-04
  • C#使用NPOI将List数据导出到Excel文档

    C#使用NPOI将List数据导出到Excel文档

    这篇文章主要为大家详细介绍了C#使用NPOI将List数据导出到Excel文档,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C#项目中引用Swagger的详细步骤和配置方式

    C#项目中引用Swagger的详细步骤和配置方式

    本文详细介绍了如何在C#项目中安装和配置Swagger,包括添加相关NuGet包、配置Swagger服务和启用Swagger中间件,还讲解了如何为API添加注释和描述,配置安全定义,以及如何使用Swagger进行API测试和调试
    2025-02-02
  • 在WPF中实现全局快捷键功能

    在WPF中实现全局快捷键功能

    这篇文章介绍了在WPF中实现全局快捷键功能的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • C#实现获取磁盘空间大小的方法

    C#实现获取磁盘空间大小的方法

    这篇文章主要介绍了C#实现获取磁盘空间大小的方法,分别基于System.IO.DriveInfo.GetDrives方法与ManagementClass("Win32_LogicalDisk")来实现这一功能,是非常实用的技巧,需要的朋友可以参考下
    2014-12-12
  • C# 启动 SQL Server 服务的实例

    C# 启动 SQL Server 服务的实例

    下面小编就为大家分享一篇C# 启动 SQL Server 服务的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • C#中System.Array.CopyTo() 和 System.Array.Clon() 的区别

    C#中System.Array.CopyTo() 和 System.Array.Clon()&nbs

    System.Array.CopyTo()和System.Array.Clone()是用于数组复制的两种不同方法,本文就来介绍C,#中System.Array.CopyTo() 和 System.Array.Clon() 的区别,具有一定的参考价值,感兴趣的可以了解一下
    2024-04-04

最新评论