现有一个word模板,实现将内容按照模板中的格式替换后,下载下来,而不是保存后,再在游览器下载一个空word。
public bool DoloadCase(string docId, string CaseText, JudicialDocument Doc)
{
CaseText = CaseText.Replace(" ", "\r\n");
//构造数据
Dictionary<string, string> datas = new Dictionary<string, string>() {
{ "{Name}", Doc.Name },
{ "{Ca}", CaseText },
{ "{Court}", Doc.CourtName },
{ "{Casenumber}", Doc.JudgeNum },
{ "{Cause}", Doc.TypeName },
{ "{JudgeDate}", Doc.JudgeDate.ToString() },
{ "{Casen}", Doc.TypeName },
{ "{Cout}", Doc.CourtName },
{ "{CaseType}",Doc.CaseType}
};
//模板文件
object path= System.Web.HttpContext.Current.Server.MapPath("/Content/DoloadCaseDetail.docx");
//生成文件
string physicNewFile =("D:/" + Doc.Name+ ".docx");
//string physicNewFile = System.Web.HttpContext.Current.Server.MapPath("/"+ Doc .Name+ ".docx");
ReplaceToWord(path, datas, physicNewFile);
return true;
}
/// <summary>
/// 根据模板生成替换文件并下载
/// </summary>
/// <param name="path">文件/模板地址</param>
/// <param name="datas">需要替换的key:value集合</param>
/// <param name="physicNewFile">生成文件地址</param>
public void ReplaceToWord(object path, Dictionary<string, string> datas, string physicNewFile)
{
Microsoft.Office.Interop.Word.Application app = null;
Microsoft.Office.Interop.Word._Document doc = null;
object oMissing = System.Reflection.Missing.Value;
try
{
app = new Microsoft.Office.Interop.Word.Application();
object fileName = path;
//打开模板文件
doc = app.Documents.Open(ref fileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
foreach (var item in datas)
{
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.ClearFormatting();
if (item.Value.Length > 220)
FindAndReplaceLong(app, item.Key, item.Value);
else
FindAndReplace(app, item.Key, item.Value);
}
在这里会保存一个word在指定设置的路径下
//对替换好的word模板另存为一个新的word文档
doc.SaveAs(physicNewFile,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
游览器会下载一个空白的Word
//准备导出word
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.Charset = "utf-8";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
System.Web.HttpContext.Current.Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (doc != null)
{
//关闭word文档
doc.Close(ref oMissing, ref oMissing, ref oMissing);
doc = null;
}
if (app != null)
{
//退出word应用程序
app.Quit(ref oMissing, ref oMissing, ref oMissing);
app = null;
}
//GC.Collect();
//GC.WaitForPendingFinalizers();
//GC.Collect();
//GC.WaitForPendingFinalizers();
//如果文件存在则输出到客户端
if (System.IO.File.Exists(physicNewFile))
{
System.Web.HttpContext.Current.Response.WriteFile(physicNewFile);
}
}
}
/// <summary>
/// 根据字符串长度执行替换操作
/// </summary>
/// <param name="wordApp">当前word程序</param>
/// <param name="findText">占位符(key)</param>
/// <param name="replaceText">替换字符串(值)</param>
public void FindAndReplaceLong(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
{
int len = replaceText.ToString().Length; //要替换的文字长度
int cnt = len / 220; //不超过220个字
string newstr;
object newStrs;
if (len < 220) //小于220字直接替换
{
FindAndReplace(wordApp, findText, replaceText);
}
else
{
for (int i = 0; i <= cnt; i++)
{
if (i != cnt)
newstr = replaceText.ToString().Substring(i * 220, 220) + findText; //新的替换字符串
else
newstr = replaceText.ToString().Substring(i * 220, len - i * 220); //最后一段需要替换的文字
newStrs = newstr;
FindAndReplace(wordApp, findText, newStrs); //进行替换
}
}
}
/// <summary>
/// 执行替换操作
/// </summary>
/// <param name="wordApp">当前word程序</param>
/// <param name="findText">占位符(key)</param>
/// <param name="replaceText">替换字符串(值)</param>
public void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
{
//object oMissing = System.Reflection.Missing.Value;
object matchCase = true;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundsLike = false;
object matchAllWordForms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiacritics = false;
object matchAlefHamza = false;
object matchControl = false;
object read_only = false;
object visible = true;
object replace = 2; //object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
object wrap = 1;
wordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceText,
ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
// wordApp.Selection.Find.Execute( ref oMissing, ref oMissing,ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref replace,
//ref oMissing, ref oMissing,ref oMissing, ref oMissing);
}