C#通过模板导出Word(文字,表格,图片)

C#通过模板导出Word(文字,表格,图片)

 

  C#导出Word,Excel的方法有很多,这次因为公司的业务需求,需要导出内容丰富(文字,表格,图片)的报告,以前的方法不好使,所以寻找新的导出方法,在网上找到了通过模板文件导出Word的方法,记录一下过程.

一:模板的创建                               

  通过模板导出,肯定需要先创建模板,然后顾名思义就是将模板中提前设置好的占位符,通过程序替换为想输出的内容即可;

  新建word文件(必须为docx或者dotx文件),放在程序根目录下,在需要位置 插入-文档部件-域,

  域名:MacroButton
  宏名:DoFieldClick
  显示文字:这个自己设置,为了与模板其他文字区分,可以用"[]"括起来.
  需要多少替换内容,添加多少域即可.

二:添加项目                                 

  在解决方案中添加项目WordMLHelper,在原项目中添加对WordMLHelper的引用后可以直接调用.
  WordMLHelper代码地址:http://url.cn/U8VNul

三:调用方法                      

  首先确定模板文件位置和导出文件的生成路径.

        private string mubanFile = "muban.docx";
        private string outputPath = @"C:UserszzDesktop	est1.docx";

  1.打开模板文件,获取所有填充域

 View Code
1 string templatePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory
2                 , mubanFile);
3             List<TagInfo> tagInfos = wordMLHelper.GetAllTagInfo(File.OpenRead(templatePath));
  2.遍历所有填充域,替换填充域内容

  锁定填充域的话,有两种方法,一是根据填充域的提示文字,如"[文字]",二是根据填充域的索引,如if(tagInfos[i].Seq==2),则是找到索引为2的填充域

 View Code

for (int i = 0; i < tagInfos.Count; i++)
{
//填充域有两种类型,1:段落或图片,2:表格
//对填充域填充时需先判断填充域类型
if (tagInfos[i].Tbl == null)
{
if (string.Equals(tagInfos[i].TagTips.Trim(), "[文字]"))
{
TxtInfo txtInfo = new TxtInfo();
txtInfo.Content = "已经成功替换";
txtInfo.ForeColor = "00ff00";
//txtInfo.HightLight = HighlightColor.Blue;
tagInfos[i].AddContent(txtInfo);
}
if (string.Equals(tagInfos[i].TagTips.Trim(), "[图片]"))
{
ImgInfo imgInfo = new ImgInfo();
imgInfo.ImgPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory
, "./image/a1.jpg");
imgInfo.Width = 200;
imgInfo.Height = 200;
tagInfos[i].AddContent(imgInfo);
}
}
else
{
TableStructureInfo tblInfo = tagInfos[i].Tbl;
if (tagInfos[i].Seq==2)
{
for (int j = 0; j < 3; j++)
{
RowStructureInfo row = new RowStructureInfo();

for (int k = 0; k < 3; k++)
{
CellStructureInfo cell = new CellStructureInfo();
TxtInfo txtInfo = new TxtInfo();
txtInfo.Content = "第" + (j + 1) + "行,第" + (k + 1) + "列";
txtInfo.Size = 25;
txtInfo.ForeColor = "0000ff";
cell.AddContentLine(txtInfo);
row.AddCell(cell);
}
tblInfo.AddRow(row);
}
}

}
}

  3.保存文件

 View Code

if (!string.IsNullOrEmpty(outputPath))
{
templatePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory
, mubanFile);
wordMLHelper.GenerateWordDocument(File.OpenRead(templatePath)
, outputPath
, tagInfos);

Assistance.RemoveAllTmpFile();// 删除所有临时文件
//Response.Redirect(Request.Url.AbsoluteUri);
}

四:完成                                        

  调用方法很简单,随着模板的修改,可以快速生成需要格式多样内容丰富的Word文档,感谢您的阅读与评论.

 
 
 
标签: Word导出
原文地址:https://www.cnblogs.com/Leo_wl/p/3509772.html