.Net Aspose.Words 生成Word文档
在开发WinForm项目中,有一需求要生成Word文档,百度学习,记录一下实现方法
NuGet包,找到 Aspose.Words 安装 21.8.0或以下 版本,否则高版本即使执行了注册码也会提示过期
一.新建一个基类
using Aspose.Words; using Aspose.Words.Tables; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; namespace DataBrowser.Common { /// <summary> /// 生成word文档 /// </summary> public class ExportOutWord { public ExportOutWord() { //需要在启动程序中执行注册码,否则生成的Word文档会有水印。 new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String( "PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGl" + "jZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZW" + "xvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pd" + "GVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4yMDA2MDIwMTI2MzM8L09yZGVySUQ+" + "CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2V" + "uc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0Pg" + "ogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOd" + "W1iZXI+OTM2ZTVmZDEtODY2Mi00YWJmLTk1YmQtYzhkYzBmNTNhZmE2PC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0" + "aW9uRXhwaXJ5PjIwMjEwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnN" + "lVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy" + "91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT5wSkpjQndRdnYxV1NxZ" + "1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhE" + "ejFiK1JIWTBuQkh1SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJ" + "vU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4="))); } /// <summary> /// 生成文档 /// </summary> public void GenerateWord(string savePath) { //过程:实例化得到word模板文件,编辑模板文件内容,再另存为新的word文件 string filePath = AppDomain.CurrentDomain.BaseDirectory + "UploadFile\\报告模板.docx"; Document doc = new Document(filePath); //这里我是放了一个空的模板,要注意得到的文件路径是绝对路径 DocumentBuilder builder = new DocumentBuilder(doc); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.BodyText; #region 第一页 AddContent(builder, "微软雅黑", true, 15, Color.Red, ParagraphAlignment.Left, "涉密资料"); Wrap(builder, 5); //换行 AddContent(builder, "微软雅黑", false, 24, Color.Black, ParagraphAlignment.Center, "标题一"); Wrap(builder, 1); AddContent(builder, "微软雅黑", false, 24, Color.Black, ParagraphAlignment.Center, "标题二"); Wrap(builder, 1); AddContent(builder, "微软雅黑", false, 24, Color.Black, ParagraphAlignment.Center, "标题三"); Wrap(builder, 4); AddContent(builder, "微软雅黑", false, 15.5, Color.Black, ParagraphAlignment.Center, DateTime.Now.ToString("yyyy.MM.dd")); #endregion builder.InsertBreak(BreakType.PageBreak); //新增页 #region 第二页 AddContent(builder, "宋体", true, 15.5, Color.Black, ParagraphAlignment.Left, "一、 报告背景"); AddContent(builder, "宋体", true, 12, Color.Black, ParagraphAlignment.Left, "1. 政策依据"); AddContent(builder, "宋体", false, 12, Color.Black, ParagraphAlignment.Left, "本报告所引用的相关政策依据为:", 24, 18); Wrap(builder, 1); AddContent(builder, "宋体", true, 12, Color.Black, ParagraphAlignment.Left, "2. 数据范围"); AddContent(builder, "宋体", false, 12, Color.Black, ParagraphAlignment.Left, "本报告使用数据来源于", 24, 18); #endregion builder.InsertBreak(BreakType.PageBreak); //新增页 #region 第三页 AddContent(builder, "宋体", true, 15.5, Color.Black, ParagraphAlignment.Left, "二、 涉嫌问题及描述"); AddContent(builder, "宋体", true, 12, Color.Black, ParagraphAlignment.Left, "1. XXX问题"); AddContent(builder, "宋体", false, 12, Color.Black, ParagraphAlignment.Left, "分析结果如下:", 24, 18); InsertTable(builder, "select row_number() over(order by Id) as 序号, [ItemName] 项目名称, [ItemMoney] [金额(元)], [ItemNum] [数量] from ViolationStatistics"); #endregion doc.Save(savePath); } /// <summary> /// 添加内容 /// </summary> /// <param name="builder"></param> /// <param name="fontName">字体的名称</param> /// <param name="bold">字体是否加粗</param> /// <param name="size">字体大小</param> /// <param name="color">字体颜色</param> /// <param name="alignment">对齐方式</param> /// <param name="content">内容</param> /// <param name="firstLineIndent">首行缩进</param> /// <param name="lineSpacing">行距</param> /// <param name="spaceBefore">段前行距</param> /// <param name="spaceAfter">段后行距</param> public void AddContent(DocumentBuilder builder, string fontName, bool bold, double size, Color color, ParagraphAlignment alignment, string content, double firstLineIndent = 0, double lineSpacing = 12, double spaceBefore = 0, double spaceAfter = 6) { builder.Font.Name = fontName; //字体的名称 builder.Font.Bold = bold; //字体加粗 builder.Font.Size = size; //字体大小 builder.Font.Color = color; //字体颜色 builder.ParagraphFormat.Alignment = alignment; //对齐方式 builder.ParagraphFormat.FirstLineIndent = firstLineIndent; //首行缩进 builder.ParagraphFormat.LineSpacing = lineSpacing; //行距 builder.ParagraphFormat.SpaceBefore = spaceBefore; //段前行距 builder.ParagraphFormat.SpaceAfter = spaceAfter; //段后行距 builder.Writeln(content); } /// <summary> /// 换行 /// </summary> /// <param name="builder"></param> public void Wrap(DocumentBuilder builder, int rowNum) { builder.Font.Size = 10.5; builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; for (int i = 0; i < rowNum; i++) { builder.Writeln(""); } } #region 添加表格(直接从数据库DataTable数据插入生成表格) public void InsertTable(DocumentBuilder builder, string sql) { List<string> listCol = new List<string>(); //表头 List<string> listText = new List<string>(); //行数据 DataTable dt = SqlHelper.ExecuteDataSet(sql).Tables[0]; foreach (DataColumn col in dt.Columns) { listCol.Add(col.ColumnName);//获取到DataColumn列对象的列名 } //文档中插入表格 Table table = builder.StartTable(); builder.RowFormat.Borders.Color = Color.Black; //插入表头 InsertCell(builder, listCol, true, 1); //渲染数据 for (int i = 0; i < dt.Rows.Count; i++) { listText = new List<string>(); foreach (string ss in listCol) { listText.Add(dt.Rows[i][ss].ToString()); } InsertCell(builder, listText, false, i % 2); } builder.EndTable(); //自动使表格适合单元格内容 table.AutoFit(AutoFitBehavior.AutoFitToContents); //表格居中对齐 table.Alignment = TableAlignment.Center; } public void InsertCell(DocumentBuilder builder, List<string> ArrText, bool bold, int a) { builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; //对齐方式 builder.ParagraphFormat.FirstLineIndent = 0; //首行缩进 builder.ParagraphFormat.SpaceAfter = 0; //段后行距 builder.ParagraphFormat.LineSpacing = 12; //行距 builder.Font.Size = 11; builder.Font.Name = "宋体"; builder.Font.Bold = bold; for (int i = 0; i < ArrText.Count; i++) { builder.InsertCell(); builder.CellFormat.Width = 100; builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; //隔行修改背景颜色 if (a == 0) { builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241); } else { builder.CellFormat.Shading.BackgroundPatternColor = Color.White; } builder.Write(ArrText[i]); } builder.EndRow(); } #endregion } }
二、获取存储路径并执行
private void btn_screport_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); string PlatName = "分析报告"; //1.打开保存窗口,自定义文件保存位置 sfd.Filter = "(*.docx)|*.docx"; sfd.FileName = PlatName + DateTime.Now.ToString("yyyyMMddHHmmss"); sfd.ShowDialog(); string saveFilePath = sfd.FileName; //获取本地指定的存储路径 ExportOutWord exportOutWord = new ExportOutWord(); exportOutWord.GenerateWord(saveFilePath); }
标签:Word,AddContent,Color,builder,ParagraphFormat,ParagraphAlignment,Black,Words,Asp From: https://www.cnblogs.com/lizongyan/p/16712052.html