首页 > 代码库 > 开源组件DocX导出Word
开源组件DocX导出Word
1、使用Docx替换Word模板里书签里内容的一个方法
using Novacode;public class ExportWord { /// <summary> /// 导出word /// </summary> /// <param name="lBookMarks">书签数据源</param> /// <param name="sTemplatePath">导出Word模板文件</param> /// <param name="sFileName">导出文件名</param> public static void ToDocx(IEnumerable<BookMarks> lBookMarks, string sTemplatePath, string sFileName) { using (DocX document = DocX.Load(sTemplatePath)) { List<Bookmark> booklist = new List<Bookmark>(); foreach (Paragraph p in document.Paragraphs) { booklist.AddRange(p.GetBookmarks()); } foreach (BookMarks m in lBookMarks) { foreach (Bookmark b in booklist) { if (b.Name == m.Name) { b.Paragraph.ReplaceText(b.Paragraph.Text, m.Text); } } } HttpContext.Current.Response.ContentType = "application/octet-stream"; string mybrowser = System.Web.HttpContext.Current.Request.Browser.Browser; if (mybrowser.ToLower().IndexOf("firefox") > -1)//火狐浏览器 { HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.docx", sFileName)); } else { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(sFileName, System.Text.Encoding.UTF8) + ".docx\""); } HttpContext.Current.Response.Clear(); document.SaveAs(HttpContext.Current.Response.OutputStream); HttpContext.Current.Response.End(); } } }
2、书签类
public class BookMarks { /// <summary> /// 书签Name /// </summary> public string Name { get; set; } /// <summary> /// 书签文本 /// </summary> public string Text { get; set; } }
3、使用示例
public void ExportTest() { List<BookMarks> bList = new List<BookMarks>(); BookMarks b = new BookMarks(); b.Name = "Title"; b.Text = "DocX导出Word Test"; bList.Add(b); b = new BookMarks(); b.Name = "Content"; b.Text = "Word正文"; bList.Add(b); ExportWord.ToDocx(bList, @"E:\Template.docx", "test"); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。