首页 > 编程语言 >.Net Aspose.Words 生成Word文档

.Net Aspose.Words 生成Word文档

时间:2022-09-20 18:36:27浏览次数:60  
标签:Word AddContent Color builder ParagraphFormat ParagraphAlignment Black Words Asp

.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

相关文章

  • ssh服务器拒绝了密码。log日志failed password for root
    环境:centos7.6软件版本:xshell5问题描述:通过xshell登录linux服务器,报错‘ssh服务器拒绝了密码’。解决过程:百度了一下,说是可能ssh配置文件有问题,修改‘PermitRootLogin......
  • 从第二章helloword开始,不记很多内容了
    1打包图片时:************************************************************************************************************2静态编译:查:deployingqtapplicatio......
  • word自动生成目录最新版本
    第一步   第二步,二级目录,最重要  注意第四步都是灰色的 ,第三步选择完后 ,选择第五步 ,然后在调整一下“点”  即可  ,另外需要注意第二步  第......
  • ueditor导入本地word并编辑
    ​图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.js,......
  • ueditor(JSP版)如何实现word文档的导入和下载功能
    ​ ueditor粘贴不能粘贴word中的图片是一个很头疼的问题,在我们的业务场景中客户要求必须使用ueditor并且支持word的图片粘贴,因为这个需求头疼了半个月,因为前端方面因为安......
  • word中公式乱码
    今天一打开word,公式全都乱码,又打开了别的word文件还是乱码,不经的心头一阵!!!具体情况如下:  解决方法:将 文件>选项>高级>显示域代码而非阈值取消勾选(在显示文档内容)......
  • ckeditor粘贴word文档图片的技术
    ​图片的复制无非有两种方法,一种是图片直接上传到服务器,另外一种转换成二进制流的base64码目前限chrome浏览器使用首先以um-editor的二进制流保存为例:打开umeditor.js,......
  • Java复制Word文档
    MicrosoftWord提供了许多易于使用的文档操作工具,同时也提供了丰富的功能集供创建复杂的文档使用。在使用的时候,你可能需要复制一个文档里面的内容到另一个文档。本文介绍......
  • ckeditor粘贴word文档图片的实例解析.
    ​ 在之前在工作中遇到在富文本编辑器中粘贴图片不能展示的问题,于是各种网上扒拉,终于找到解决方案,在这里感谢一下知乎中众大神以及TheViper。通过知乎提供的思路找到粘......
  • 怎么把word文件插入到公众号文章中
    怎么把word文件插入到公众号文章中呢?相信,这是很多公众号运营师经常会遇到的情境。因为,在日常的公众号运营中,他们经常需要在文章中添加一些附件,比如:登记表、申请表、报名表......