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

最新文章

  1. 动态dynamically变更母版_Layout页body标签css的class
  2. MMORPG大型游戏设计与开发(part1 of net)
  3. 注解:【无连接表的】Hibernate单向1-&gt;N关联
  4. JMeter性能监测插件介绍(三)
  5. CSS 3 颜色表示法
  6. Hibernate实现向数据库插入一条数据全过程(Study By Example)
  7. jQuery easyui 之 expend row
  8. 关于HTML中,绝对定位,相对定位的理解...(学习HTML过程中的小记录)
  9. Codeforces Round #308 (Div. 2) A. Vanya and Table 暴力
  10. 【BZOJ1251】序列终结者
  11. 机器学习基石的泛化理论及VC维部分整理(第六讲)
  12. 我的开发框架(WinForm)3
  13. iosAPP打包上架xcode中Archive提交成功以后,不提示构建版本问题
  14. 项目管理实践教程二、源代码控制【Source Control Using VisualSVN Server and TortoiseSVN】
  15. php 10.2总
  16. JS 响应式编程
  17. 让Win10显示系统中隐藏的文件夹
  18. while求1+2+3+4+5+6....100的和
  19. python测试开发django-3.url配置
  20. mybatis + oracle insert clob,出现ORA-01461:仅能绑定要插入LONG列的LONG值

热门文章

  1. Mybatis自动生成插件对数据库类型为text的处理
  2. json序列化字符串后,配置枚举类型显示数值而不是名称
  3. centos 7.0运行docker出现内核报错解决方法
  4. MacBook Pro装Win7后喇叭没有声音
  5. ACM入门问题:最大利益问题
  6. c语言中的malloc函数
  7. 【HBase】快速搞定HBase与Hive的对比、整合
  8. 你真的知道C语言里extern "C" 的作用吗?
  9. [hdu5217]线段树
  10. flink优化总结