c# html 转word

C# html保存为word文件两种方式:

var content = "";

//如果图片或者链接不是绝对路径,需要把相对路径转化为绝对路径,否则word里面图片显出不出来
string hostpath = Request.Url.AbsoluteUri.ToString().Substring(0, Request.Url.AbsoluteUri.ToString().Length - Request.Url.LocalPath.ToString().Length + 1);
Regex rx = new Regex(@"(?<=src="")(.*?)(?="")", RegexOptions.IgnoreCase | RegexOptions.Singleline);
content = rx.Replace(content, hostpath + "$1");
rx = new Regex(@"(?<=href="")(.*?)(?="")", RegexOptions.IgnoreCase | RegexOptions.Singleline);
content = rx.Replace(content, hostpath + "$1");


//1.通过浏览器转word,直接下载
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=result.doc");
System.Web.HttpContext.Current.Response.ContentType = "application/msword";
System.Web.HttpContext.Current.Response.Charset = "utf-8";
System.Web.HttpContext.Current.Response.Write(content);
System.Web.HttpContext.Current.Response.End();

//2.直接选择目录地址保存为word
//var Path = "D:\\新建文件夹\\result2.doc";//word文件保存路径
//sw = new StreamWriter(Path, false, Encoding.GetEncoding("utf-8"));
//sw.WriteLine(content);
//sw.Flush();
//sw.Close();

posted @ 2018-11-20 15:57  桐人oc  阅读(1723)  评论(0编辑  收藏  举报