此篇博文是用后端技术实现,前端实现请看我另一篇博文
string serverPath = path + "/Export/ywRpt/" + dtAllRpt.Rows[i]["EnglishName"].ToString() + ".docx";//使用模板路径
downLoadPath = path + "/Export/ywRptDownload/" + DateTime.Parse(stime).ToString("yyyyMM") + "/" + sstation + "/" + dtAllRpt.Rows[i]["EnglishName"].ToString() + ".docx";//下载文件路径;
string p = path + "/Export/ywRptDownload/" + DateTime.Parse(stime).ToString("yyyyMM") + "/" + sstation + "/";//创建文件夹路径
if (!System.IO.File.Exists(p))
{
Directory.CreateDirectory(p); //如果文件夹不存在,则创建
}
//复制一份
File.Copy(serverPath, downLoadPath, true);
Aspose.Words.Document doc = new Document(downLoadPath);
Aspose.Words.DocumentBuilder builder = new DocumentBuilder(doc);
//遍历生成多个独立doc
for (int i = 100; i >= 0; i--){
doc.Range.Bookmarks[key].Text = "√";//根据标签Bookmarks属性名赋值
doc.Save(downLoadPath, Aspose.Words.SaveFormat.Doc);//生成100个doc
}
//将生成好的100个doc合并在一个doc,并生成目录
if (dtZGNR != null && dtZGNR.Rows.Count > 0)
{
for (int i = dtZGNR.Rows.Count - 1; i >= 0; i--)
{
string docFileUrl = path + dtZGNR.Rows[i]["FileURL"].ToString();
FileInfo fi = new FileInfo(docFileUrl);
if (fi.Exists)//如果文件存在
{
Aspose.Words.Document d = new Document(docFileUrl);
if (d.Range.Bookmarks["xu_hao"] != null)
{
d.Range.Bookmarks["xu_hao"].Text = ((dtZGNR.Rows.Count - i - weeknum)).ToString();
}
doc.AppendDocument(d, ImportFormatMode.UseDestinationStyles);
}
}
}
//在指定标签位置创建目录
builder.MoveToBookmark("dateYM", false, true);
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");//目录格式
doc.UpdateFields();
//doc.Range.Bookmarks["mu_lu"].Text = string.Empty;// 清掉标示
string downLoadPath=doc.Save(downLoadPath, Aspose.Words.SaveFormat.Doc);
return downLoadPath; //返回输出doc路径