C# 使用Word模板导出数据的实现代码

 更新时间:2021年06月23日 10:50:20   作者:沙漠狼  
最近接到个需求,使用word模板导出数据,怎么实现这个需求呢,今天小编通过实例代码给大家介绍C# 使用Word模板导出数据的方法,感兴趣的朋友一起看看吧

使用NPOI控件导出数据到Word模板中方式:

效果如下:

Word模板:

运行结果:

实现如下:

Student.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExportWord
{
    public class Student
    {
        public String Photo
        {
            get;
            set;
        }
        public FileStream PhotoData
        {
            get;
            set;
        }
        public String Name
        {
            get;
            set;
        }

        public List<Course> Data
        {
            get;
            set;
        }
    }
}

Course.cs

using System;

namespace ExportWord
{
    public class Course
    {
        public String Name { get; set; }
        public Int32 Score { get; set; }
    }
}

Main.cs

public FileStream Export()
        {
            Student stu = new ExportWord.Student();
            stu.Name = "AAAAA";
            stu.Photo = @"C:\Users\hutao\Pictures\2019-12-16_153943.png";
            stu.PhotoData = new FileStream(stu.Photo, FileMode.Open, FileAccess.Read);

            stu.Data = new List<Course>();
            stu.Data.Add(new ExportWord.Course() { Name = "BBBB", Score = 89 });
            stu.Data.Add(new ExportWord.Course() { Name = "CCCC", Score = 90 });
            stu.Data.Add(new ExportWord.Course() { Name = "DDDD", Score = 100 });
            stu.Data.Add(new ExportWord.Course() { Name = "EEEE", Score = 101 });
            stu.Data.Add(new ExportWord.Course() { Name = "FFFF", Score = 102 });
            stu.Data.Add(new ExportWord.Course() { Name = "GGGG", Score = 103 });

            string path = Application.StartupPath;

            string filepath = (path + @"\template.docx");
            using (FileStream stream = File.OpenRead(filepath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍历段落
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKey(para, stu);
                }
                //遍历表格
                var tables = doc.Tables;
                foreach (var table in tables)
                {
                    ReplaceTableKey(table, stu.Data, "Data");
                }

                foreach (var table in tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKey(para, stu);
                            }
                        }
                    }
                }

                FileStream out1 = new FileStream(path + @"\123.docx", FileMode.Create);
                doc.Write(out1);
                out1.Close();
                return out1;
            }

        }

ReplaceKey()

/// <summary>
        /// 替换Key
        /// </summary>
        /// <param name="para"></param>
        /// <param name="model"></param>
        private static void ReplaceKey(XWPFParagraph para, object model)
        {
            string text = para.ParagraphText;
            var runs = para.Runs;
            string styleid = para.Style;
            for (int i = 0; i < runs.Count; i++)
            {
                var run = runs[i];
                text = run.ToString();
                Type t = model.GetType();
                PropertyInfo[] pi = t.GetProperties();
                foreach (PropertyInfo p in pi)
                {
                    if (p.PropertyType.Name == "FileStream")
                    {
                        if (text.Contains("$" + p.Name + "$"))
                        {
                            runs[i].SetText("", 0);
                            runs[i].AddPicture((FileStream)p.GetValue(model, null), (int)PictureType.JPEG, "image1", 1000000, 1000000);
                        }
                    }
                    else
                    {
                        //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一
                        if (text.Contains("$" + p.Name + "$"))
                        {
                            text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString());
                            runs[i].SetText(text, 0);
                        }
                    }
                }
            }
        }

ReplaceTableKey()

/// <summary>
        /// 替换表格Key
        /// </summary>
        /// <param name="para"></param>
        /// <param name="model"></param>
        private static void ReplaceTableKey(XWPFTable table, IList list, String field)
        {
            List<XWPFParagraph> paras = new List<XWPFParagraph>();
            // 获取最后一行数据,最后一行设置值
            Int32 iLastRowIndex = 0;
            for (int iIndex = 0; iIndex < table.Rows.Count; iIndex++)
            {
                if (iIndex == table.Rows.Count - 1)
                {
                    iLastRowIndex = iIndex;
                    foreach (var cell in table.Rows[iIndex].GetTableCells())
                    {
                        foreach (var para in cell.Paragraphs)
                        {
                            paras.Add(para);
                        }
                    }
                }
            }
            // 删除最后一行
            table.RemoveRow(iLastRowIndex);

            for (int iIndex = 0; iIndex < list.Count; iIndex++)
            {
                dynamic data = list[iIndex];
                Type t = data.GetType();
                PropertyInfo[] pi = t.GetProperties();
                // 表增加行
                XWPFTableRow m_row = table.CreateRow();
                CT_Row m_NewRow = new CT_Row();
                String text = String.Empty;
                Int32 jIndex = 0;
                paras.ForEach(para =>
                {
                    text = para.ParagraphText;
                    foreach (PropertyInfo p in pi)
                    {
                        if (text.Contains("$" + field + "." + p.Name + "$"))
                        {
                            m_row.GetCell(jIndex).SetText(p.GetValue(data, null).ToString());
                        }
                    }
                    jIndex++;
                });
                m_row = new XWPFTableRow(m_NewRow, table);
                table.AddRow(m_row);

            }
        }
protected void btn_Click(object sender, EventArgs e)
        {
            using (FileStream fs = Export())
            {
                string path = Application.StartupPath;
                //将byte数组写入文件中
                DownloadFile(fs);
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="URL">下载文件地址</param>
        /// <param name="Filename">下载后另存为(全路径)</param>

        private bool DownloadFile(FileStream fs)
        {
            try
            {
                byte[] by = new byte[fs.Length];
                fs.Write(by, 0, by.Length);
                fs.Close();
                return true;
            }
            catch (System.Exception e)
            {
                return false;
            }
        }

以上就是C# 使用Word模板导出数据的详细内容,更多关于C# 导出数据的资料请关注脚本之家其它相关文章!

相关文章

  • 总结C#删除字符串数组中空字符串的几种方法

    总结C#删除字符串数组中空字符串的几种方法

    C#中要如何才能删除一个字符串数组中的空字符串呢?下面的文章会介绍多种方式来实现清除数组中的空字符串,以及在.net中将字符串数组中字符串为空的元素去除。
    2016-08-08
  • WinForm中comboBox控件数据绑定实现方法

    WinForm中comboBox控件数据绑定实现方法

    这篇文章主要介绍了WinForm中comboBox控件数据绑定实现方法,结合实例形式分析了WinForm实现comboBox控件数据绑定的常用方法与相关操作技巧,需要的朋友可以参考下
    2017-05-05
  • C# TcpClient网络编程传输文件的示例

    C# TcpClient网络编程传输文件的示例

    这篇文章主要介绍了C# TcpClient网络编程传输文件的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
    2021-04-04
  • c#和net存取cookies操作示例

    c#和net存取cookies操作示例

    这篇文章主要介绍了c#和net存取cookies操作示例,需要的朋友可以参考下
    2014-02-02
  • 浅析C#数据类型转换的几种形式

    浅析C#数据类型转换的几种形式

    本篇文章是对C#中数据类型转换的几种形式进行了详细的分析介绍,需要的朋友参考下
    2013-07-07
  • C#学习笔记之飞行棋项目

    C#学习笔记之飞行棋项目

    这篇文章主要为大家详细介绍了C#控制台实现飞行棋项目,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • 一篇文章彻底搞清楚c#中的委托与事件

    一篇文章彻底搞清楚c#中的委托与事件

    这篇文章主要给大家介绍了如何通过一篇文章彻底搞清楚c#中的委托与事件,文中通过示例代码介绍的非常详细,对大家学习或者使用c#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-07-07
  • C# 基础入门--常量

    C# 基础入门--常量

    本文主要介绍了C#中常量的相关知识,具有很好的参考价值。下面跟着小编一起来看下吧
    2017-03-03
  • C#操作DataTable方法实现过滤、取前N条数据及获取指定列数据列表的方法

    C#操作DataTable方法实现过滤、取前N条数据及获取指定列数据列表的方法

    这篇文章主要介绍了C#操作DataTable方法实现过滤、取前N条数据及获取指定列数据列表的方法,实例分析了C#操作DataTable的各种常用技巧,非常具有实用价值,需要的朋友可以参考下
    2015-04-04
  • C# TreeView控件使用技巧汇总

    C# TreeView控件使用技巧汇总

    这篇文章主要介绍了C# TreeView控件使用技巧汇总,TreeView控件在窗体应用里面使用也是频率比较高的,我们在使用TreeView一般是对资源的分层展示,类似数据结构里面树的凹入表示法
    2022-08-08

最新评论