利用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文件中还定义了表格样式、图样式、图标题样式、表标题样式。