打开word模板
代码语言:javascript复制private DocumentBuilder builder; // a reference to Word application
private Aspose.Words.Document oDoc; // a reference to the document
/// <summary>
/// 打开有模板的word
/// </summary>
/// <param name="strFileName">模板名称</param>
public void OpenWithTemplate(string strFileName)
{
if (!string.IsNullOrEmpty(strFileName))
{
oDoc = new Aspose.Words.Document(strFileName);
builder = new DocumentBuilder(oDoc);
}
}
语句介绍:
代码语言:javascript复制//插入目录代码(TOC)
WriteText("目录", 16, false, "center");
builder.InsertTableOfContents("\o "1-3" \h\z\u");
//更新目录(不使用更新目录会导致页码对不上)
oDoc.UpdateFields();//添加在保存文件之前
//添加一级目录
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
WriteText(item.text, 16, true, "center");
//转到书签
builder.MoveToBookmark(radio);
//往模板里面添加固定表格的数据
wordDoc.MailMerge.ExecuteWithRegions(table);//集合赋值遍历
//插入图片
builder.InsertImage(imgpath)
//添加超链接
builder.InsertHyperlink(img[0], aa, false);
//对齐
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
//换行
builder.InsertBreak(BreakType.LineBreak);
//分页
builder.InsertBreak(BreakType.PageBreak);
//插入书签BookMark书签名称
builder.StartBookmark(BookMark);
builder.EndBookmark(BookMark);
builder.Writeln("");
//清除所有书签
oDoc.Range.Bookmarks.Clear();
//将上述设定的格式清除
builder.Font.ClearFormatting();
//插入表格
builder.StartTable();//开始画Table
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
//添加Word表格 //循环添加行
for (int row = 0; row < dt.Rows.Count; row )
{
builder.RowFormat.Height = 20;
//循环添加列
for (int col = 0; col < dt.Columns.Count; col )
{
builder.InsertCell();
builder.Font.Size = 12.0;
builder.Bold = false;
builder.Font.Name = "宋体";
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
builder.CellFormat.Width = 100.0;
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(100);
if (haveBorder == true)
{
//设置外框样式
builder.CellFormat.Borders.LineStyle = LineStyle.Single;
//样式设置结束
}
var sss = dt.Rows[row][col].ToString();
builder.InsertHtml(sss);
//oWordApplic.Write(dt.Rows[row][col].ToString());
}
builder.EndRow();//结束行
}
builder.EndTable();//表格结束
添加内容
代码语言:javascript复制/// <summary>
/// 添加内容 (输出后换行)
/// </summary>
/// <param name="strText"></param>
/// <param name="conSize"></param>
/// <param name="conBold"></param>
/// <param name="conAlign"></param>
public void WriteText(string strText, double conSize, bool conBold, string conAlign)
{
builder.Bold = conBold;
builder.Font.Name = "宋体";
builder.Font.Size = conSize;
switch (conAlign)
{
case "left":
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
break;
case "center":
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
break;
case "right":
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
break;
default:
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
break;
}
builder.Writeln(strText);
}
导出实例
代码语言:javascript复制/// <summary>
/// 导出---
/// </summary>
/// <param name="FileNameUrl">模板路径</param>
/// <returns></returns>
public MemoryStream GetExportExpertIdea(string FileNameUrl)
{
MemoryStream mStream = new MemoryStream();
try
{
Document wordDoc = new Document(FileNameUrl);//打开模板文件
string[] fieldNames = new string[] {
"KTName",
"KTAssumeUnit",
"KTResUser",
"STimeETime" ,
"UTime",
"KTAssumeUnit",
"KTUpdaterID",
"Name",
"Sex",
"Age",
};
string[] fieldValues = new string[] {
"1",
"2",
"3",
"4",
"4" ,
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
};
wordDoc.MailMerge.Execute(fieldNames, fieldValues);//域赋值
DataTable table = new DataTable("TableCY");
table.Columns.Add("CYName");
table.Columns.Add("CYSex");
table.Columns.Add("CYAge");
table.Columns.Add("CYDutyTitle");
table.Columns.Add("CYExpertise");
table.Columns.Add("CYDevoteTime");
table.Columns.Add("CYWorkPlace");
List<object> list = new List<object>();
for (int i = 0; i < P01_Member.Count; i )
{
list = new List<object>();
list.Add("姓名");
list.Add("男");
list.Add("18");
list.Add("");
list.Add(""");
list.Add("");
list.Add("");
table.Rows.Add(list.ToArray());
}
wordDoc.MailMerge.ExecuteWithRegions(table);//集合赋值遍历
wordDoc.Save(mStream, SaveFormat.Doc);
return mStream;
}
catch (Exception ex)
{
return mStream;
}
}
/// <summary>
/// 导出
/// </summary>
/// <returns></returns>
[HttpGet, HttpHead, Route("ContractTemplate"), AllowAnonymous]
public IHttpActionResult ContractTemplate()
{
if (!id.HasValue)
{
return ResponseMessage(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.OK);
//生成合同保存路径。
string FileUrl = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "模板名称.docx");;
var mes = ServiceFactory.Get<IDeclaration>().GetContractTemplate(FileUrl);
Stopwatch sw = Stopwatch.StartNew();
var browser = String.Empty;
if (Request.Headers.UserAgent != null)
{
browser = Request.Headers.UserAgent.ToString().ToUpper();
}
var fileName ="模板名称.docx";
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(mes.ToArray())
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
//response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") // 设置头部其他内容特性, 文件名
{
FileName = browser.Contains("FIREFOX") ? fileName : HttpUtility.UrlEncode(fileName)
};
sw.Stop();
Console.WriteLine(sw.Elapsed);
return ResponseMessage(response);
}
前端js文件:
代码语言:javascript复制 download() {
let url = '/api/declaration/ContractTemplate';
axios({
methods: 'get',
url: url,
responseType: 'blob'
}).then(res => {
const blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
let contentDisposition = res.headers['content-disposition']; //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; f
let patt = new RegExp("filename=([^;] \.[^\.;] );*");
let result = patt.exec(contentDisposition);
let filename = decodeURI(result[1]);
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename)
} else {
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob) // 创建下载的链接
downloadElement.href = href
downloadElement.download = filename // 下载后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 点击下载
document.body.removeChild(downloadElement) // 下载完成移除元素
window.URL.revokeObjectURL(href) // 释放掉blob对象
}
})
.catch(function (error) {
that.showMessage(error, 'error');
})
.then(function () {
that.endLoading();
});
}
},
模板:
其中TableStart:和TableEnd:为固定语法 TableCY 为表格名称(自定义和代码里面的匹配就行)
添加域操作方式:
用offcie打开word,选择插入文档部件,选择里面域。如果是表格:KTname 换成 TableStart:TableCY,结尾换成end