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

http://www.cnblogs.com/kingteach/archive/2011/11/22/2258801.html

Wythe

随笔 - 35  文章 - 15  评论 - 24

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);

        }

 

        /// <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# 根据Word模版生成Word文件

 

分类: CommonUtil

标签: c# word 模版 导出

好文要顶 关注我 收藏该文 C# 根据Word模版生成Word文件 C# 根据Word模版生成Word文件

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

Wythe
关注 - 2
粉丝 - 10

+加关注

2

0

« 上一篇:sql 日期函数
» 下一篇:MessageBoxUtil(转)

posted @ 2011-11-22 14:45 Wythe 阅读(8280) 评论(4) 编辑 收藏

评论列表

  

#1楼2013-07-30 15:35 _YMW  

怎么调用啊?GenerateWord这个方法传入的参数看不太懂。请指教

支持(0)反对(0)

  

#2楼2014-04-14 17:01 cherry1986  

同问

支持(0)反对(0)

  

#3楼2014-09-19 10:07 WaitingEver  

同上啊

支持(0)反对(0)

  

#4楼[楼主] 2014-09-19 10:13 Wythe  

@ WaitingEver
/// <summary>
/// 模版包含头部信息和表格,表格重复使用
/// </summary>
/// <param name="dt">重复表格的数据</param>
/// <param name="expPairColumn">word中要替换的表达式和表格字段的对应关系</param>
/// <param name="simpleExpPairValue">简单的非重复型数据</param>
有注释啊

支持(0)反对(0)

刷新评论刷新页面返回顶部

注册用户登录后才能发表评论,请 登录 或 注册访问网站首页。

【推荐】超50万VC++源码: 大型组态工控、电力仿真CAD与GIS源码库!
【推荐】如何快速搭建人工智能应用?
【大赛】2018首届“顶天立地”AI开发者大赛

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

最新IT新闻:
· 小米正式发布区块链产品“米粒”
· 上海市消保委:高德地图等APP申请权限与实际功能不完全对应
· AMD股价今年已增长61% 分析师预测12个月内冲击21美元
· 外媒:中兴通讯据悉已偿还4亿美元3年期银团贷款
· 何小鹏购买小米股票后,雷军前往小鹏汽车参观
» 更多新闻...

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

最新知识库文章:

· 危害程序员职业生涯的三大观念
· 断点单步跟踪是一种低效的调试方法
· 测试 | 让每一粒尘埃有的放矢
· 从Excel到微服务
· 如何提升你的能力?给年轻程序员的几条建议

» 更多知识库文章...

公告

昵称:Wythe
园龄:8年11个月
粉丝:10
关注:2

+加关注

< 2011年11月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

搜索

 

 

常用链接

我的标签

随笔分类

随笔档案

最新评论

阅读排行榜

评论排行榜

推荐排行榜

Copyright ©2018 Wythe