欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#根據(jù)Word模版生成Word文件

 更新時間:2017年10月27日 16:27:29   作者:大西瓜3721  
這篇文章主要為大家詳細介紹了C#根據(jù)Word模版生成Word文件的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了C#根據(jù)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">重復表格的數(shù)據(jù)</param>
    /// <param name="expPairColumn">word中要替換的表達式和表格字段的對應關系</param>
    /// <param name="simpleExpPairValue">簡單的非重復型數(shù)據(jù)</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#訪問SqlServer設置鏈接超時的方法

    C#訪問SqlServer設置鏈接超時的方法

    這篇文章主要介紹了C#訪問SqlServer設置鏈接超時的方法,涉及CommandTimeout屬性的相關設置技巧,非常簡單實用,需要的朋友可以參考下
    2015-06-06
  • 淺談C# 類的繼承

    淺談C# 類的繼承

    本文主要介紹了C# 類的繼承相關知識。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-01-01
  • C#設計模式之觀察者模式實例講解

    C#設計模式之觀察者模式實例講解

    這篇文章主要介紹了C#設計模式之觀察者模式實例講解,本文詳細講解了觀察者模式的定義、優(yōu)缺點、代碼實例等,需要的朋友可以參考下
    2014-10-10
  • 避免在C#循環(huán)中使用await的方法小結

    避免在C#循環(huán)中使用await的方法小結

    在C#中,異步編程因其能夠提升應用程序性能和響應能力而變得越來越流行,async和await關鍵字使得編寫異步代碼變得更加容易,但如果使用不當,它們也可能引入一些陷阱,所以本文我們將探討為什么應該避免在C#循環(huán)中使用await,并討論一些更高效地處理異步操作的替代方法
    2024-09-09
  • C#計算器編寫代碼

    C#計算器編寫代碼

    這篇文章主要為大家分享了C#計算器編寫代碼,供大家參考,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-07-07
  • C#迷你猜數(shù)實例分析

    C#迷你猜數(shù)實例分析

    這篇文章主要介紹了C#迷你猜數(shù),實例分析C#操作數(shù)字及數(shù)組的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-03-03
  • C#通過System.CommandLine快速生成支持命令行的應用程序

    C#通過System.CommandLine快速生成支持命令行的應用程序

    這篇文章介紹了C#通過System.CommandLine快速生成支持命令行應用程序的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-07-07
  • C#自定義的方法實現(xiàn)堆棧類設計

    C#自定義的方法實現(xiàn)堆棧類設計

    這篇文章主要為大家詳細介紹了如何使用C#創(chuàng)建一個帶有Push方法和Clist類的CStack類,并如何在其中添加和遍歷堆棧數(shù)據(jù),感興趣的可以了解下
    2024-03-03
  • C# Volatile的具體使用

    C# Volatile的具體使用

    本文主要介紹了C# Volatile的具體使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-11-11
  • C# Socket的TCP通訊的實例代碼

    C# Socket的TCP通訊的實例代碼

    本篇文章主要介紹了C# Socket的TCP通訊,socket通訊方式有兩種:同步和異步,詳細的介紹了這兩種方法,有興趣的可以了解一下。
    2016-12-12

最新評論