首页 > 代码库 > Asp.net通过模板(.dot)导出Word
Asp.net通过模板(.dot)导出Word
需要引用Office的DLL,在附件中
贴上核心代码(转载):
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 = "年龄"; //第四步 生成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 = http://www.mamicode.com/Type.Missing;>
服务端生成后,附加简单的流下载代码:
1 string fileName = "表.doc";//客户端保存的文件名 2 string filePath = Server.MapPath("~/Download//Word//Table1.doc");//路径 3 4 //以字符流的形式下载文件 5 FileStream fs = new FileStream(filePath, FileMode.Open); 6 byte[] bytes = new byte[(int)fs.Length]; 7 fs.Read(bytes, 0, bytes.Length); 8 fs.Close(); 9 Response.ContentType = "application/octet-stream";10 //通知浏览器下载文件而不是打开11 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));12 Response.BinaryWrite(bytes);13 Response.Flush();14 Response.End();
附上各个Office版本Dll库:
各个版本的microsoft.office.interop.word库.rar
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。