使用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

Export()
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 = });
stu.Data.Add(new ExportWord.Course() { Name = "CCCC", Score = });
stu.Data.Add(new ExportWord.Course() { Name = "DDDD", Score = });
stu.Data.Add(new ExportWord.Course() { Name = "EEEE", Score = });
stu.Data.Add(new ExportWord.Course() { Name = "FFFF", Score = });
stu.Data.Add(new ExportWord.Course() { Name = "GGGG", Score = }); 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 = ; 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("", );
runs[i].AddPicture((FileStream)p.GetValue(model, null), (int)PictureType.JPEG, "image1", , );
}
}
else
{
//$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一
if (text.Contains("$" + p.Name + "$"))
{
text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString());
runs[i].SetText(text, );
}
}
}
}
}

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 = ;
for (int iIndex = ; iIndex < table.Rows.Count; iIndex++)
{
if (iIndex == table.Rows.Count - )
{
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 = ; 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 = ;
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, , by.Length);
fs.Close();
return true;
}
catch (System.Exception e)
{
return false;
}
}

C# 使用Word模板导出数据的更多相关文章

  1. Net Core DocXCore 实现word模板导出

    实际工作中,往往有这样的需求,需要导出word,还有各种各样的样式,于是有了word模板导出. 实现以下几个需求: 1.表单导出 2.表格导出 3.表单表格混合导出 4.实际用例测试 解决方案: 实现 ...

  2. SpringBoot集成文件 - 如何基于POI-tl和word模板导出庞大的Word文件?

    前文我们介绍了通过Apache POI通过来导出word的例子:那如果是word模板方式,有没有开源库通过模板方式导出word呢?poi-tl是一个基于Apache POI的Word模板引擎,也是一个 ...

  3. MiniWord .NET Word模板引擎,藉由Word模板和数据简单、快速生成文件。

    Github / Gitee QQ群(1群) : 813100564 / QQ群(2群) : 579033769 介绍 MiniWord .NET Word模板引擎,藉由Word模板和数据简单.快速生 ...

  4. 无插件,无com组件,利用EXCEL、WORD模板做数据导出(一)

    本次随笔主要讲述着工作中是如何解决数据导出的,对于数据导出到excel在日常工作中大家还是比较常用的,那导出到word呢,改如何处理呢,简单的页面导出问题应该不大,但是如果是标准的公文导出呢,要保证其 ...

  5. word模板导出的几种方式:第一种:占位符替换模板导出(只适用于word中含有表格形式的)

    1.占位符替换模板导出(只适用于word中含有表格形式的): /// <summary> /// 使用替换模板进行到处word文件 /// </summary> public ...

  6. .net core 使用NPOI填充Word模板导出Word

    最近工作用到在Word模板插入数据库数据,导出一个带数据的Word文件,想起来之前操作Word都是用微软提供的Microsoft.Office.Interop.Word,而在最新的..NET CORE ...

  7. 利用模板导出文件(二)之jacob利用word模板导出word文件(Java2word)

    https://blog.csdn.net/Fishroad/article/details/47951061?locationNum=2&fps=1 先下载jacob.jar包.解压后将ja ...

  8. OpenXml Sdk 根据Word模板导出到word

    一:OpenXml Sdk 简介 Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档.演示文稿和电子表格的国际化开放标准,可免费供多个应用 ...

  9. 8、jeecg 笔记之 自定义word 模板导出(一)

    1.前言 jeecg 中已经自带 word 的导出导出功能,其所使用的也是 easypoi,尽管所导出的 word 能满足大部分需求, 但总是有需要用到自定义 word导出模板,下文所用到的皆是 ea ...

随机推荐

  1. 27.rm命令

    rm命令可以删除指定的文件或目录.也可以将某个目录及其下属的所有文件及其子目录均删除掉.对于链接文件,只是删除整个链接文件,而原有文件保持不变. 选项:-f:强制删除. -r:递归处理,将指定目录下的 ...

  2. 如何将Superset嵌入后台系统之实践

    1. 前言 此次实践过程全属个人学习,我选择了在window下安装Superset,并进行嵌入后台系统实践.对此进行实践过程总结,实践成果分享给大家,供大家参考,如果你有更好的想法,欢迎留言交流. 2 ...

  3. Python抓取新浪新闻数据(二)

    以下是抓取的完整代码(抓取了网页的title,newssource,dt,article,editor,comments)举例: 转载于:https://blog.51cto.com/2290153/ ...

  4. 数学--数论--HDU 6128 Inverse of sum (公式推导论)

    Description 给nn个小于pp的非负整数a1,-,na1,-,n,问有多少对(i,j)(1≤i<j≤n)(i,j)(1≤i<j≤n)模pp在意义下满足1ai+aj≡1ai+1aj ...

  5. 2019 ICPC 银川网络赛 D. Take Your Seat (疯子坐飞机问题)

    Duha decided to have a trip to Singapore by plane. The airplane had nn seats numbered from 11 to nn, ...

  6. App 自动化环境搭建

    1.安装 Appium-desktop 工具 下载地址:https://github.com/appium/appium-desktop/releases 2.安装 Android 环境 安装 JDK ...

  7. MySQL 中 on与where筛选条件的区别

    在两张表连接的时候才会有on的筛选条件,那么on和where的区别是什么呢? 在inner join中是没有区别的,但是在左连接和右连接中,区别就体现出来了,下面以左连接为例: 1.用on的时候,只对 ...

  8. 基于thinkphp3.2.3开发的CMS内容管理系统(二)- Rbac用户权限

    基于thinkphp3.2.3开发的CMS内容管理系统 thinkphp版本:3.2.3 功能: --分类栏目管理 --文章管理 --商品管理 --用户管理 --角色管理 --权限管理 --友情链接管 ...

  9. CentOS安装配置nginx和php

    今天买了台阿里云服务器用于日常开发测试(新人9块钱半年).系统版本CentOS 6.5 64位. 首先安装nginx: yum install nginx 参考文档: 在CentOS 6上搭建LNMP ...

  10. quartus II Warning 好的时序是设计出来的,不是约束出来的

    一.Warning (15714): Some pins have incomplete I/O assignments. Refer to the I/O Assignment Warnings r ...