/// <summary>
/// 生产word 文档
/// </summary>
public class GenerateWord
{
/// <summary>
///模板地址
/// </summary>
public string TempPath { get; set; } /// <summary>
/// 保存地址
/// </summary>
public string SavePath { get; set; } /// <summary>
/// 页眉数据
/// </summary>
public Hashtable HsHeads { get; set; } /// <summary>
/// 页脚数据
/// </summary>
public Hashtable HsFoots { get; set; } /// <summary>
/// 书签数据
/// </summary>
public Hashtable HsBookMark { get; set; } /// <summary>
/// 文档内容
/// </summary>
public DataSet DsBody { get; set; } /// <summary>
/// 文档名称
/// </summary>
public string FileName { get; set; }
public string EmptyLogo { get; set; }
private Thread thread; public void SaveTemplate()
{
DocX document = DocX.Load(TempPath); #region 生成页面页脚 Formatting f = new Formatting();
f.FontColor = Color.FromArgb(, , );
f.Size = ;
f.Bold = true;
f.FontFamily = new FontFamily("Helvetica"); Formatting ffoot = new Formatting();
ffoot.FontColor = Color.Black;
ffoot.Size = ;
ffoot.FontFamily = new FontFamily("Helvetica"); document.AddHeaders(); //添加所有页眉
Headers heads = document.Headers; //获取该文档所有的页眉
Header hfirst = heads.first;
Header head1 = heads.even;
Header head2 = heads.odd; hfirst.InsertParagraph(HsBookMark["MerchantName"].ToString(), false, f).Direction = Direction.RightToLeft;
head1.InsertParagraph(HsBookMark["MerchantName"].ToString(), false, f).Direction=Direction.RightToLeft;
head2.InsertParagraph(HsBookMark["MerchantName"].ToString(), false, f).Direction=Direction.RightToLeft; document.AddFooters();//添加所有的页脚
Footers footers = document.Footers; //获取该文档所有的页脚
Footer ffirst = footers.first;
Footer feven = footers.even;
Footer fodd = footers.odd; document.DifferentFirstPage = true;
document.DifferentOddAndEvenPages = true; Paragraph pf = ffirst.InsertParagraph(HsFoots["comp_name"].ToString(), false, ffoot);
Paragraph pfeven = feven.InsertParagraph(HsFoots["comp_name"].ToString(), false, ffoot);
Paragraph pfodd = fodd.InsertParagraph(HsFoots["comp_name"].ToString(), false, ffoot); //添加logo
Novacode.Image img;
MemoryStream stmMemory = new MemoryStream(); Paragraph p = head1.InsertParagraph("", false);
if (HsHeads["LogoUrl"] == null || HsHeads["LogoUrl"].ToString() == "")
{ System.Drawing.Image myimg = System.Drawing.Image.FromFile(EmptyLogo);
myimg.Save(stmMemory, myimg.RawFormat); // 保存你的图片到memorystream
stmMemory.Seek(, SeekOrigin.Begin);
img = document.AddImage(stmMemory);
}
else
{
System.Net.WebRequest webreq = System.Net.WebRequest.Create(HsHeads["LogoUrl"].ToString());//"http://www.bc.ccoo.cn/logo/logo.gif"
System.Net.WebResponse webres = webreq.GetResponse();
Stream stream = webres.GetResponseStream();
System.Drawing.Image myimg = System.Drawing.Image.FromStream(stream);
myimg.Save(stmMemory, myimg.RawFormat); // 保存你的图片到memorystream
stmMemory.Seek(, SeekOrigin.Begin);
img = document.AddImage(stmMemory);
stream.Close();
} string footmark = string.Format("地址:{0} 电话:{1} QQ:{2}", HsFoots["address"].ToString(), HsFoots["tel"].ToString(), HsFoots["qq"].ToString());
//将图像插入到段落后面
Picture pic = img.CreatePicture(); //选择图像,并修改图像尺寸
pic.Rotation = ;
pic.Width = ;
pic.Height = ; //设置图片形状,并水平翻转图片
pic.SetPictureShape(BasicShapes.cube);
pic.FlipHorizontal = false; pf.InsertPicture(pic, );
pf.Direction = Direction.RightToLeft;
pf.InsertParagraphAfterSelf(footmark, false, ffoot); pfeven.InsertPicture(pic);
pfeven.Direction = Direction.RightToLeft;
pfeven.InsertParagraphAfterSelf(footmark, false, ffoot); pfodd.InsertPicture(pic);
pfodd.Direction = Direction.RightToLeft;
pfodd.InsertParagraphAfterSelf(footmark, false, ffoot); #endregion #region 替换文本 document.ReplaceText("$ReportTitle$", HsBookMark["MerchantName"].ToString());
document.ReplaceText("$r_year$", DateTime.Now .Year.ToString());
document.ReplaceText("$r_month$", DateTime.Now.Month.ToString());
document.ReplaceText("$Report_head$", HsBookMark["OperatingCommissioner"].ToString()); document.ReplaceText("$IP$", HsBookMark["IPNUM"].ToString());
document.ReplaceText("$PV$", HsBookMark["PVNUM"].ToString());
document.ReplaceText("$FK$", HsBookMark["FKNUM"].ToString()); document.ReplaceText("$UserFeedBack$", HsBookMark["UserFeedback"].ToString());
document.ReplaceText("$ThinkingMonth$", HsBookMark["ThinkingMonth"].ToString());
document.ReplaceText("$ThinkingNextMonth$", HsBookMark["ThinkingNextMonth"].ToString()); #endregion #region 替换表格数据
Table t = document.Tables[];
if (t != null)
{
//生成Pv流量
if (DsBody.Tables.Count > && DsBody.Tables[].Rows.Count > )
{
List<Cell> listcell = t.Rows[].Cells;
listcell[].Paragraphs[].Append(DsBody.Tables[].Columns[].ColumnName.ToString()).Alignment = Alignment.center;
listcell[].Paragraphs[].Append(DsBody.Tables[].Columns[].ColumnName.ToString()).Alignment = Alignment.center;
listcell[].Paragraphs[].Append(DsBody.Tables[].Columns[].ColumnName.ToString()).Alignment = Alignment.center; for (int i = ; i < t.Rows.Count; i++)
{
listcell = t.Rows[i].Cells;
for (int j = ; j < ; j++)
{
listcell[j + ].Paragraphs[].Append(DsBody.Tables[].Rows[i - ][j].ToString()).Alignment = Alignment.center;
}
}
}
} #endregion #region 动态生成表格
//生成运维日志
if (DsBody.Tables.Count > && DsBody.Tables[].Rows.Count > )
{
for (int i = ; i < DsBody.Tables[].Rows.Count; i++)
{
CreateAndInsertTableAfter(ref document, DsBody.Tables[].Rows[i], Convert.ToString(i + ), HsBookMark["OperatingCommissioner"].ToString());
}
}
#endregion
//声明内存流
MemoryStream ms = new MemoryStream();
//文件保存到内存流
document.SaveAs(ms);
document.Dispose();
#region 更新数据库 //更新数据库
//发送到远处服务器进行保存
#endregion
} private static Table CreateAndInsertTableAfter(ref DocX document,DataRow dr,string indexnum,string head)
{
#region 定义字体颜色
Formatting f1 = new Formatting();
f1.FontColor = Color.White;
f1.Size = ;
f1.Bold = true;
f1.FontFamily = new FontFamily("Helvetica"); Formatting f2 = new Formatting();
f2.FontColor = Color.FromArgb(, , );
f2.Size = ;
f2.Bold = true;
f2.FontFamily = new FontFamily("Helvetica"); Formatting f3 = new Formatting();
f3.FontColor = Color.FromArgb(, , );
f3.Size = ;
f3.Bold = true;
f3.FontFamily = new FontFamily("Helvetica"); Formatting f4 = new Formatting();
f4.FontColor = Color.FromArgb(, , );
f4.Size = ;
f4.Bold = true;
f4.FontFamily = new FontFamily("Helvetica"); Formatting f5 = new Formatting();
f5.FontColor = Color.FromArgb(, , );
f5.Size = ;
f5.Bold = true;
f5.FontFamily = new FontFamily("Helvetica"); Formatting f6 = new Formatting();
f5.FontColor = Color.FromArgb(, , );
f5.Size = ;
f5.FontFamily = new FontFamily("Helvetica");
#endregion Table table = document.InsertTable(, ); table.AutoFit = AutoFit.ColumnWidth; #region Table title table.Rows[].Height = ; List<Cell> listtable = table.Rows[].Cells;
listtable[].Paragraphs[].InsertText(indexnum, false, f1);
listtable[].MarginTop = ;
listtable[].FillColor = Color.FromArgb(, , );
listtable[].Width = ;
listtable[].Paragraphs[].Alignment = Alignment.center; listtable[].FillColor = Color.FromArgb(, , );
listtable[].Paragraphs[].InsertText(dr["systime"].ToString() + "/" + (dr["OpMan"].ToString() == "" ? head : dr["OpMan"].ToString()), false, f6);
listtable[].Paragraphs[].Alignment = Alignment.right;
listtable[].Width = ; List<Cell> listtable1 = table.Rows[].Cells;
listtable1[].Paragraphs[].InsertText("行动", false, f2);
listtable1[].Width = ;
listtable1[].Paragraphs[].Alignment = Alignment.center; listtable1[].Paragraphs[].InsertText(dr["dowhat"].ToString(), false, f6);
listtable1[].Paragraphs[].Alignment = Alignment.left; List<Cell> listtable2 = table.Rows[].Cells;
listtable2[].Paragraphs[].InsertText("原因", false, f3);
listtable2[].Width = ;
listtable2[].Paragraphs[].Alignment = Alignment.center; listtable2[].Paragraphs[].InsertText(dr["reason"].ToString(), false, f6);
listtable2[].Paragraphs[].Alignment = Alignment.left; List<Cell> listtable3 = table.Rows[].Cells;
listtable3[].Paragraphs[].InsertText("作用", false, f4);
listtable3[].Width = ;
listtable3[].Paragraphs[].Alignment = Alignment.center; listtable3[].Paragraphs[].InsertText(dr["effect"].ToString(), false, f6);
listtable3[].Paragraphs[].Alignment = Alignment.left; List<Cell> listtable4 = table.Rows[].Cells;
listtable4[].Paragraphs[].InsertText("结果", false, f5);
listtable4[].Width = ; listtable4[].Paragraphs[].Alignment = Alignment.center;
Novacode.Image img;
MemoryStream stmMemory = new MemoryStream();
if (dr["PicUrl"] != null && dr["PicUrl"].ToString() != "")
{
System.Net.WebRequest webreq = System.Net.WebRequest.Create(dr["PicUrl"].ToString());
System.Net.WebResponse webres = webreq.GetResponse();
Stream stream = webres.GetResponseStream();
System.Drawing.Image myimg = System.Drawing.Image.FromStream(stream);
myimg.Save(stmMemory, myimg.RawFormat); // 保存你的图片到memorystream
stmMemory.Seek(, SeekOrigin.Begin);
img = document.AddImage(stmMemory);
stream.Close();
listtable4[].Paragraphs[].InsertPicture(img.CreatePicture(, ));
}
else
{
var hrefresult = Regex.Match(dr["result"].ToString(), @"(?<=[\s+]?href[\s+]?=[\s+]?('|"")?)[^(""|')>]+?(?=""|')");
if (hrefresult.ToString() != "")
{
Hyperlink link = document.AddHyperlink("点击查看结果", new Uri(hrefresult.ToString()));
listtable4[].Paragraphs[].AppendHyperlink(link);
}
else
{
hrefresult = Regex.Match(dr["result"].ToString(), @"http://www.*");
if (hrefresult.ToString() != "")
{
Hyperlink link = document.AddHyperlink("点击查看结果", new Uri(hrefresult.ToString()));
listtable4[].Paragraphs[].AppendHyperlink(link);
}
else
{
listtable4[].Paragraphs[].Append(dr["result"].ToString());
}
}
} listtable4[].Paragraphs[].Alignment = Alignment.left; #endregion table.Alignment = Alignment.center;
table.InsertParagraphAfterSelf("",false).AppendLine().AppendLine();
return table;
}
public GenerateWord(string TempPath, string FileName, string EmptyLogo, string SavePath, Hashtable HsHeads, Hashtable HsFoots, Hashtable HsBookMark, DataSet DsBody)
{
this.TempPath = TempPath;
this.SavePath = SavePath;
this.EmptyLogo = EmptyLogo;
this.HsHeads = HsHeads;
this.HsFoots = HsFoots;
this.HsBookMark = HsBookMark;
this.FileName = FileName;
this.DsBody = DsBody;
thread = new Thread(new ThreadStart(SaveTemplate));
}
public void Start()
{
if (thread != null)
{
thread.Start();
}
}
}

Docx 生成word文档二的更多相关文章

  1. Docx 生成word文档

    1.生成word代码 /// <summary> /// 生成word文档 /// </summary> /// <param name="tempPath&q ...

  2. PoiDocxDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0),目前只能java生成】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这个是<PoiDemo[Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)]>的扩展,上一篇是根 ...

  3. PoiDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 使用Poi实现android中根据模板文件生成Word文档的功能.这里的模板文件是doc文件.如果模板文件是docx文件的话,请阅读 ...

  4. C# 动态生成word文档 [C#学习笔记3]关于Main(string[ ] args)中args命令行参数 实现DataTables搜索框查询结果高亮显示 二维码神器QRCoder Asp.net MVC 中 CodeFirst 开发模式实例

    C# 动态生成word文档 本文以一个简单的小例子,简述利用C#语言开发word表格相关的知识,仅供学习分享使用,如有不足之处,还请指正. 在工程中引用word的动态库 在项目中,点击项目名称右键-- ...

  5. C#开源组件DocX处理Word文档基本操作(二)

    上一篇 C#开源组件DocX处理Word文档基本操作(一) 介绍了DocX的段落.表格及图片的处理,本篇介绍页眉页脚的处理. 示例代码所用DocX版本为:1.3.0.0.关于版本的区别,请参见上篇,而 ...

  6. 将HTML导出生成word文档

    前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...

  7. POI生成word文档完整案例及讲解

    一,网上的API讲解 其实POI的生成Word文档的规则就是先把获取到的数据转成xml格式的数据,然后通过xpath解析表单式的应用取值,判断等等,然后在把取到的值放到word文档中,最后在输出来. ...

  8. Android根据word模板文档将表单数据生成word文档的方案整理

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 尝试的方案包括以下几种: freemarker 只能在java项目上运行,无法在Android项目上运行: 参考资料:<Fre ...

  9. Aspose.Words简单生成word文档

    Aspose.Words简单生成word文档 Aspose.Words.Document doc = new Aspose.Words.Document(); Aspose.Words.Documen ...

随机推荐

  1. BezierCode 工具使用

    概要 今天无意间看到一个视频,发现了一款绘画Bezier 图形绘制并自动生成OC代码的神器, 因此马上先记录下. 之前一直很纠结如果程序员自己去绘制图片,久那么使用bezier 自己去画吗? 答案是: ...

  2. StringUtils工具

    ppublic class StringUtils { private StringUtils() { } /** * 文本左边补零 * * @param maxLength 文本长度 * @para ...

  3. JS流程控制语句 退出循环break 在while、for、do...while、while循环中使用break语句退出当前循环,直接执行后面的代码。

    退出循环break 在while.for.do...while.while循环中使用break语句退出当前循环,直接执行后面的代码. 格式如下: for(初始条件;判断条件;循环后条件值更新) { i ...

  4. springBoot_JPA和lombok

    一.JPA 特点:JPA可以根据方法名自动匹配sql语句. JPA是一个标准 Hibernate是JPA的一个实现,宗旨是尽量少写sql语句. 使用JPA 1.application.properti ...

  5. PAT甲级——A1009 Product of Polynomials

    This time, you are supposed to find A×B where A and B are two polynomials. Input Specification: Each ...

  6. Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1

    Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be res ...

  7. Python学习day16-模块基础

    <!doctype html>day16 - 博客 figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { ...

  8. [TJOI2017]城市 【树的直径+暴力+优化】

    Online Judge:Luogu P3761 Label:树的直径,暴力 题目描述 从加里敦大学城市规划专业毕业的小明来到了一个地区城市规划局工作.这个地区一共有n座城市,n-1条高速公路,保证了 ...

  9. hdu4764

    hdu4764bash博弈主要是找准必胜状态,以及好好理解题意.这里的必胜状态是n-1,虽然是写的数比上一个大1到k,但是相当于这个人拿1到k,然后是累加的效果 #include<iostrea ...

  10. mysqlbinlog: unknown variable 'default-character-set=utf8'

    [xxx@dbhost log]$ mysqlbinlog mysql-bin. mysqlbinlog: unknown variable 'default-character-set=utf8' ...