Asp.net通过模板(.dot/Html)导出Word,同时导出图片

时间:2021-09-10 15:21:34

一、Office组件导出Word(服务器配置麻烦)

需要引用Office的DLL,在下文的附件中,不同的Offic版本用的不一样,虽然高级版本可以兼容低级的,不过,还是统一版本最好

贴上核心代码(转载):

         Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word._Document docFile = null;
try
{
appWord.Visible = false;
object objTrue = true;
object objFalse = false;
object objTemplate = Server.MapPath(@"dot//123.dot");//模板路径
object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;
docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);
//第一步生成word文档
//定义书签变量
object obDD_Name = "DD_Name";//姓 名
object obDD_Sex = "DD_Sex";//性 别
object obDD_Age = "DD_Age";//年龄
object obDD_Birthday = "DD_Birthday"; //出生年月
object obDD_Nation = "DD_Nation"; //民 族
object obDD_Native = "DD_Native"; //籍 贯 //第二步 读取数据,填充数据集
//SqlDataReader dr = XXXXX;//读取出来的数据集
//第三步 给书签赋值
//给书签赋值
docFile.Bookmarks.get_Item(ref obDD_Name).Range.Text = "姓 名"; //姓 名
docFile.Bookmarks.get_Item(ref obDD_Sex).Range.Text = "性 别";
docFile.Bookmarks.get_Item(ref obDD_Age).Range.Text = "年龄";        //存入图片
object objTrue = true;
docFile.Bookmarks.get_Item("Photo").Range.InlineShapes.AddPicture(HttpContext.Current.Server.MapPath(@"" + imgUrl), ref miss, ref objTrue, ref miss);
//第四步 生成word
DateTime dt = DateTime.Now;
object filename = Server.MapPath("dot//") + "表" + dt.Ticks.ToString() + ".doc";
object miss = System.Reflection.Missing.Value;
docFile.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
object missingValue = Type.Missing;
object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Quit(ref miss, ref miss, ref miss);
docFile = null;
appWord = null;
}
catch (Exception ex)
{
//捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
string aa = e.ToString();
object miss = System.Reflection.Missing.Value;
object missingValue = Type.Missing;
object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Quit(ref miss, ref miss, ref miss);
docFile = null;
appWord = null;
throw ex;
}

服务端生成后,附加简单的流下载代码:

                 string fileName = "表.doc";//客户端保存的文件名
string filePath = Server.MapPath("~/Download//Word//Table1.doc");//路径 //以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, , bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

附上各个Office版本Dll库:

各个版本的microsoft.office.interop.word库.rar

二、通过htm模板导出(此方法简单,无需word组件支持!样式标准,不过有些缺陷,导出图片比较麻烦,而且,效果不好)

1、本地新建一个Word文档,然后编写文档格式,文字填充部分用{Title}等特殊标记表示,方便替换。

2、另存文档为网页格式(Htm、Html)。

3、将生成的模板网页放在网站目录下。

4、上代码:

 protected void Button1_Click(object sender, EventArgs e)
{
string strWord = ExprotMissionToWord(Server.MapPath("Temp.htm"));
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=magazineturn.doc");
Response.AddHeader("Content-type", "application");
Response.ContentType = "application/ms-html";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.Write(strWord);
Response.Flush();
Response.Close();
} public string ExprotMissionToWord(string templatePath)
{
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader(templatePath, Encoding.Default);
sb.Append(sr.ReadToEnd());
sr.Close();
sb.Replace("{title}", "我是标题");
sb.Replace("{content} ", "我是正文");
return sb.ToString();
}

内容应该通俗易懂了,全部都是基础方法,就不细说了。

简单的说明一下,原理,是IO读取这个模板,然后替换掉设置的特殊字符,然后输出,ok!完成。