先引用Aspose.Words類庫,然後創建一個Word模板,我現在的需求是有一個模板頁,但是需要多個相同的模板頁數量也不一定,就需要創建需要多頁模板頁,但是創建的時候書籤是會有變化的,現在分享一下心得。
//模板路徑
string WordTemplate = Server.MapPath("~/Files/Template/Word/模板.doc");
//實例化
Document doc = new Document(WordTemplate);
//把原模板複製下來
Document doc3 = doc.Clone();
int j = 0;
int k = 0;
//取得的數據條數
k = Data.Count();
//服務器臨時文件夾 這個是創建多個模板頁的文件夾,並且刪除創建過的模板頁
string wordPath = Server.MapPath("~/Files/Template/TempWord/");
if (!Directory.Exists(wordPath))
{
Directory.CreateDirectory(wordPath);
}
//通過等到的數據創建模板頁
for (int i = 0; i < k - 1; i++)
{
doc3.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting);
}
//保存新的模板頁
doc3.Save(wordPath + "New_模板.doc");
//實例化新的模板頁
Document doc2 = new Document(wordPath + "New_模板.doc");
//循環數據 書籤替換
foreach (var item in Data)
{
//查找到書籤標籤
foreach (Bookmark mark in doc2.Range.Bookmarks)
{
//複製書籤標籤後標籤會自動添加數字下標
string Name = "Name_" + j;
string Bill_Money = "Bill_Money_" + j;
string PayCode = "PayCode_" + j;
if (mark != null)
{
if (mark.Name == "Name" || mark.Name == Name)
{
mark.Text = !string.IsNullOrEmpty(Currencyitem.FirstOrDefault().CstmNameC) ? Currencyitem.FirstOrDefault().CstmNameC : !string.IsNullOrEmpty(Currencyitem.FirstOrDefault().CstmNameE) ? Currencyitem.FirstOrDefault().CstmNameE : " ";
}
else if (mark.Name == "PayCode" || mark.Name == PayCode)
{
mark.Text = Currencyitem.FirstOrDefault().VendorCode;
}
else if (mark.Name == "Bill_Money" || mark.Name == Bill_Money)
{
decimal? Sum_M = Currencyitem.Where(o => true).Sum(o => o.WeiHeXiaoJinEr);
mark.Text = ExchangRate.FirstOrDefault(o => o.ExchangeRateType == Currencyitem.Key).TypeNameJX + Decimal.Round((decimal)Sum_M, 2);
}
}
j++;
}
//保存新的Word
wordpathname = wordPath + "付款申請書" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
doc2.Save(wordpathname);
}
FileInfo fileInfo = new FileInfo(wordpathname);
下載保存得Word