以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权;而且Office安装,包括权限配置也是比较麻烦。

现在流行使用第三方组件来实现对Office的操作,有NPOI,Spire等第三方组件。开始考虑的是NPOI,毕竟它在操作Excel方面还是很强大的;但是不知道是它本身没有,还是我没找到,无法实现利用Word模板的标签插入内容,纯靠代码去生成Word文档,排版是个大问题。最终找到了Spire.Doc组件,轻松实现!

  Spire的官网地址:https://www.e-iceblue.com/

1、项目中引用 Free Spire.Doc 组件,我是直接用NuGet下载包的.

安装完后,会引用其三个组件:

2、Word 模板制作

打开Word,点击 文件->选项->自定义功能区,勾选上“开发工具”:

主要使用文本域控件,插入作为标签:

如果有需要,可以添加“下划线”,或者“字符边框”等效果:

底下三个,前2个我用的是开发工具中的复选框(窗体控件)效果不是勾选的,是×号,效果不是客户想要的,所以使用了第二种解决方案“字符边框”,最后看导出的效果:

3、代码

可重用代码:

 using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace We.Framework.Spire
{
/// <summary>
/// Sprie.Doc
/// Designed by XIAO
/// 2017-05-09
/// </summary>
public class WordHandler
{
public static bool ExportWordByFields<T>(T mod, string TempleteFilePath, string ExpFilePath)
{
if (mod == null)
{
throw new Exception("模型为空!");
} System.Reflection.PropertyInfo[] properties = mod.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (properties.Length <= )
{
throw new Exception("模型属性为空!");
} if (!File.Exists(TempleteFilePath))
{
throw new Exception("指定路径的模板文件不存在!");
} try
{
Document doc = new Document();
doc.LoadFromFile(TempleteFilePath); #region 替换文字
//doc.Replace("海关", "海关口岸", true, true);
//doc.Replace("报验", "报检", true, true);
#endregion //清除表单域阴影
doc.Properties.FormFieldShading = false; //遍历Word模板中的文本域(field.name为文本域名称)
foreach (FormField field in doc.Sections[].Body.FormFields)
{
foreach (System.Reflection.PropertyInfo prop in properties)
{
string name = prop.Name; //属性名称
object value = prop.GetValue(mod, null); //属性值
string des = ((DescriptionAttribute)Attribute.GetCustomAttribute(prop, typeof(DescriptionAttribute))).Description;// 属性描述值 //注意:文本域名称 == 模型中属性的 Description 值 !!!!!!
//也可以: 文本域名称 == 模型中属性的 Name 值 !!!!!!
if (field.Name == des)
{
if (field.DocumentObjectType == DocumentObjectType.TextFormField) //文本域
{
if (prop.PropertyType.Name == "Boolean")
{
field.Text = "√"; //插入勾选符号
break;
}
else
{
field.Text = value.ToString(); //向Word模板中插入值
break;
}
}
else if (field.DocumentObjectType == DocumentObjectType.CheckBox) //复选框
{
(field as CheckBoxFormField).Checked = (value as bool?).HasValue ? (value as bool?).Value : false;
}
}
}
} doc.SaveToFile(ExpFilePath, FileFormat.Docx);
doc.Close(); return true;
}
catch (Exception ex)
{
string msg = ex.Message; return false;
}
}
}
}

测试代码部分:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace WordHelper.TestModel
{
/// <summary>
/// 抽样记录单
/// </summary>
public class SamplingRcd
{
[Description("记录单编号")]
public string No { get; set; } [Description("年")]
public int Year { get; set; } [Description("月")]
public int Month { get; set; } [Description("日")]
public int Day { get; set; } [Description("药品名称")]
public string DrugName { get; set; } [Description("商品名")]
public string GoodsName { get; set; } [Description("注册证号")]
public string RegistNo { get; set; } [Description("检验通知号")]
public string NoticeNo { get; set; } [Description("外包装是否完整")]
public bool IsIntact { get; set; } [Description("是否封固")]
public bool IsFixed { get; set; } [Description("铅封")]
public bool IsPb { get; set; }
}
}

数据模型

         private void button1_Click(object sender, EventArgs e)
{
SamplingRcd mod = new SamplingRcd();
mod.No = "No158922144";
mod.Year = ;
mod.Month = ;
mod.Day = ;
mod.DrugName = "门冬胰岛素50注射液";
mod.GoodsName = "康胰素";
mod.RegistNo = "R12324552";
mod.NoticeNo = "N12324552";
mod.IsIntact = true;
mod.IsFixed = true;
mod.IsPb = true; System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
string templeteFileName = @"..\..\WordTemplete\进口药品抽样记录单.docx";
string newFileName = string.Format("H:\\Exp_进口药品抽样记录单_{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmss")); bool result = WordHandler.ExportWordByFields<SamplingRcd>(mod, templeteFileName, newFileName);
if (result)
{
MessageBox.Show("成功");
}
else
{
MessageBox.Show("失败");
}
}

基本功能已经实现,还有待改进,希望各位提出宝贵意见!

(PS:如果有朋友知道NPOI如何实现类似功能的,望告知下!先谢谢了!^_^)

使用Spire.Doc组件利用模板导出Word文档的更多相关文章

  1. poi根据模板导出word文档

    POI结构与常用类 Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI ...

  2. Struts2利用iText导出word文档(包含表格)以提供下载

    J2EE ExcelStrutsXML  在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以word文档形式下载课表.将课表导出到excel里的功能他们已经实现了, ...

  3. 利用标签导出Word文档

    1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; us ...

  4. 利用NPOI导出Word文档帮助类

    /// <summary> /// NPOI操作Word /// </summary> public class NpoiWordHelper { /// <summar ...

  5. 前台导出Word文档思路步骤总结(freemarker)

    1. 需求是导出word带表格,表格列数不变,行数由数据库的值决定: 2. 导出最开始想的是直接前端导出,使用了jquery-wordexport插件,导出后,表格边框全没了,无法使用: 3. 采用了 ...

  6. .NET通过调用Office组件导出Word文档

    .NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...

  7. C#导出Word文档开源组件DocX

    1.帮助文档,这东西找了很久,而且它版本很旧,还是英文,W8.1系统上打不开 http://download.csdn.net/detail/zuofangyouyuan/7673573 2.开源网址 ...

  8. JSP利用freemarker生成基于word模板的word文档

    利用freemarker生成基于word模板的word文档 freemarker简介 FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出.FreeMarker与Web容器 ...

  9. Java 用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

随机推荐

  1. 关于MFC中InvalidateRect()的思考与疑问

    先看一段代码: void CFeatureEdit_LinePolyDLG::DrawRectAll(int type){ CClientDC dc(this); //底框画笔 CPen penRec ...

  2. linux 安装sysstat使用iostat、mpstat、sar、sa

    使用yum安装 #yum install sysstat sysstat的安装包是:sysstat-5.0.5-1.i386.rpm,装完了sysstat-5.0.5-1.i386.rpm后 就会有i ...

  3. Java常量笔记

    在添加文件名的同时,文件名和内容可以不相同!! 1·Java 常量 常量就是固定不变的量,一旦被定义,它的值就不能被改变. 例实: 书中的代码不全,在这里不补充一下: 书中的源代码: public c ...

  4. MCMC(一)蒙特卡罗方法

    MCMC(一)蒙特卡罗方法 MCMC(二)马尔科夫链(待填坑) MCMC(三)M-H采样和Gibbs采样(待填坑) 作为一种随机采样方法,马尔科夫链蒙特卡罗(Markov Chain Monte Ca ...

  5. Redis + keepalived 高可用群集搭建

    本次实验环境介绍: 操作系统: Centos 7.3 IP : 192.168.10.10 Centos 7.3 IP : 192.168.10.20  VIP    地址   : 192.168.1 ...

  6. Java基础—String类小结

    一.String类是什么 public final class String implements java.io.Serializable, Comparable<String>, Ch ...

  7. [原]node.js使用感想

    最近尝试了使用node.js,但因为不是太深入(小项目,还没做完),所以不能谈心得谈经验,就来谈谈使用感想. node.js和以往的cgi接口的服务器+cgi程序(如apache+phpmod)中的单 ...

  8. 老李分享:robotium3.6与4.0 later 的区别 1

    老李分享:robotium3.6与4.0 later 的区别   因为下载的直接是最新版本的robotium4.1版,这次碰到gridView问题时,发现网上有getCurrentListViews( ...

  9. python urllib模块

    1.urllib.urlopen(url[,data[,proxies]]) urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象,然后像 ...

  10. 使用mysql索引技巧及注意事项

    一.索引的作用 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,所以查询语句的优化显然是重中之重. 在数据 ...