Aspose.Words利用word样式写入标题及正文(.NET)

利用aspose生成word报告时,需要用代码定义样式,如字体大小、字体颜色等。可能面临以下场景:
1、用户需要更改样式
2、报告本身具有多种样式。
则需要更改代码。
为此,可考虑以自带样式的word为模板文件(即doc文件或docx),利用用户已经定义好的样式去输出报告。

首先制作word模板文件

1、注意样式的名称最好是改成英文,如title1等。
在这里插入图片描述
在这里插入图片描述

C#获取word样式,样式比较多,由于样式较多,注意选择使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Words;
using System.Collections;

namespace OperateWord
{
    class BLL
    {

        public void NewWord()
        {
            string tempPath = @"E:\文档\visual studio 2015\Projects\OperateWord\wordFiles\template2.docx";
            string path = @"E:\文档\visual studio 2015\Projects\OperateWord\wordFiles\template2-1.docx";
            Document doc = new Document(tempPath);
            StyleCollection styles = doc.Styles;
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.ParagraphFormat.Style = styles["Title1"];
            builder.Writeln("HTTU大学");
             
            builder.ParagraphFormat.Style = styles["Title2"];
            builder.Writeln("地球学院");
            builder.ParagraphFormat.Style = styles["Heading 2"];
            builder.Writeln("交通学院");

            builder.ParagraphFormat.Style = styles["Title3"];
            builder.Writeln("交通工程专业");
            builder.ParagraphFormat.Style = styles["Heading 3"]; //word自己的命名,等同于Title3。为避免出错,最好还是使用自己命名的样式名。
            builder.Writeln("桥梁工程专业");

            builder.ParagraphFormat.Style = styles["text"];
            builder.Writeln("桥梁工程专业是我院最具特色的专业之一,已经为全球公司输送了上万名劳工!");
            doc.Save(path, SaveFormat.Docx);
        }

    }
}


生成效果

在这里插入图片描述

补充说明

除了标题样式外,该word文件中还定义了表格样式、图样式、图标题样式、表标题样式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值