C# html保存为word文件

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

第一种:通过浏览器输出的方式

#region 读取html 
var html = GetBidTempStrng();//读取html内容
#endregion

#region 转换为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(html);
System.Web.HttpContext.Current.Response.End();
#endregion

第二种:直接转换保存为word文件

private static StreamWriter sw;

try
{     
    var html = GetBidTempStrng();//读取html内容
    var Path = "D:\\File\\Test\\result2.doc";//word文件保存路径
    sw = new StreamWriter(Path, false, Encoding.GetEncoding("utf-8"));
    sw.WriteLine(html);
    sw.Flush();
    sw.Close();
}
catch (Exception ex)
{
    throw new Exception(ex.Message, ex);
}
注:

1.读取html内容的方法

private string GetBidTempStrng()
{
    StringBuilder sbHtml = new StringBuilder();
    // html的地址
    var path = Server.MapPath("/File/LowPricePolicyAgreement.html");
    using (Stream inStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
    using (StreamReader outStream = new StreamReader(inStream, Encoding.Default))
    {
        while (!outStream.EndOfStream)
        {
            sbHtml.Append(outStream.ReadLine());
        }
    }
    var html = sbHtml.ToString();
    return html;
}

2.分享一个在线word完美转换为html的地址

点击打开链接

你可能感兴趣的:(.net)