protected void btnExport_Click(object sender, EventArgs e)
{
string strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
string sHtml = hfdHtml.Value;//前台的HTML传递过来的,注意加ValidateRequest="false"
string sMht = HtmlToMht(sHtml);
DnLoadFileFromMemoryStream(strFileName, sMht);
} /// <summary>
/// 将HTML文本导出到Word或者MHT格式
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToMht(string strHtml)
{
strHtml = strHtml.Replace("<", "<").Replace(">", ">");
StringBuilder sb = new StringBuilder();
sb.AppendLine("From:");
sb.AppendLine("Subject:");
sb.AppendLine("Date:");
sb.AppendLine("MIME-Version: 1.0");
sb.AppendLine("Content-Type: multipart/related;");
sb.AppendLine("\ttype=\"text/html\";");
sb.AppendLine("\tboundary=\"----=_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"");
sb.AppendLine("\n");
sb.AppendLine("------=_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
sb.AppendLine("Content-Type: text/html;");
sb.AppendLine("charset=\"gb2312\"");
sb.AppendLine("Content-Transfer-Encoding: quoted-printable");
sb.AppendLine("\n");
sb.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
sb.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
sb.AppendLine("<head>");
sb.AppendLine("<style>");
sb.AppendLine("@page WordSection1");
sb.AppendLine("{size:532.5pt 757.5pt;");
sb.AppendLine("mso-page-orientation:poPortrait;");
sb.AppendLine("margin:26.25pt 26.25pt 26.25pt 26.25pt;");
sb.AppendLine("mso-header-margin:42.55pt;");
sb.AppendLine("mso-footer-margin:49.6pt;");
sb.AppendLine("mso-paper-source:0;}");
sb.AppendLine("div.WordSection1");
sb.AppendLine("{page:WordSection1;}");
sb.AppendLine("</style>");
sb.AppendLine("</head>");
sb.AppendLine("<body>");
sb.AppendLine("<div class=3DWordSection1>");
sb.AppendLine(strHtml.Replace("src=", "src=3D").Replace("style=\"", "style= \\\"")).Replace("rowSpan=", "rowSpan=\\\"")
.Replace("colSpan=", "colSpan=\\\"").Replace("width=", "width=\\\"").Replace("height=", "height=\\\"");
sb.AppendLine("</div>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
sb.AppendLine("\n");
string[] imgSrcs = GetHtmlImageUrlList(strHtml);
if (imgSrcs.Length > 0)
{
for (int i = 0; i < imgSrcs.Length; i++)
{
string strLink = imgSrcs[i];
string strBianm = ConvertBase64(strLink);
if (strBianm != "")
{
sb.AppendLine("\n");
sb.AppendLine("------=_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
sb.AppendLine("Content-Type: image/jpeg");
sb.AppendLine("Content-Transfer-Encoding: base64");
sb.AppendLine("Content-Location: " + strLink);
sb.AppendLine("\n");
sb.AppendLine(strBianm);
sb.AppendLine("\n");
}
}
}
sb.AppendLine("------=_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA--");
return sb.ToString();
} /// <summary>
/// 更改Img等HTML标签从相对路径改为绝对路径,注意HTML里初始化时是什么路径,在后台就是什么路径,它不会在后台变为绝对路径,所以有必要转换一下,不然导出的图片不能显示
/// </summary>
/// <param name="sHtmlText"></param>
/// <returns></returns>
public static string[] GetHtmlImageUrlList(string sHtmlText)
{
// 定义正则表达式用来匹配 img 标签
Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = regImg.Matches(sHtmlText);
int i = 0;
string[] sUrlList = new string[matches.Count];
// 取得匹配项列表
foreach (Match match in matches)
sUrlList[i++] = match.Groups["imgUrl"].Value;
return sUrlList;
} /// <summary>
/// 将图片转换为Base64位格式字符串流
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public static string ConvertBase64(string filepath)
{
//变量
string result = string.Empty;
string path = string.Empty;
if (filepath.Trim().Substring(0, 4) == "http")
{
result = string.Empty;
}
else
{
path = HttpContext.Current.Server.MapPath(filepath);
//将文件转换为stream
using (FileStream fs = new FileStream(path, FileMode.Open))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
result = Convert.ToBase64String(buffer); //base64编码
}
}
//返回编码后的字符串
return result;
} /// <summary>
/// 将文本流转换为word流
/// </summary>
/// <param name="sFileName"></param>
/// <param name="sContent"></param>
public static void DnLoadFileFromMemoryStream(string sFileName, string sContent)
{
byte[] arrByte = Encoding.UTF8.GetBytes(sContent);
using (MemoryStream ms = new MemoryStream())
{
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);
HttpContext.Current.Response.BinaryWrite(arrByte);
}
}

HTML页面导出为Word的更多相关文章

  1. aspx页面导出为word

    aspx页面导出为word代码: System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWri ...

  2. (转)WEB页面导出为Word文档后分页&横向打印的方法

    <html>    <HEAD>        <title>WEB页面导出为Word文档后分页&横向打印的方法 </title>    < ...

  3. c# 将页面导出到word(含图片及控件)

    /// <summary> /// 创建word /// <param name="filePath">文件路径 </param> /// &l ...

  4. PHP 将html页面导出至Word

    <?php header("Content-Type: application/msword"); header("Content-Disposition: att ...

  5. 【MVC】 非常简单的页面导出 WORD, EXCEL方法

    [MVC] 页面导出 WORD, EXCEL 前端 js function output() { var para = new Object(); para.html = getHtml(" ...

  6. Java 实现HTML富文本导出至word完美解决方案

    一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现 ...

  7. javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页

    由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...

  8. 将HTML导出生成word文档

    前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...

  9. 网页导出成word文档的默认视图方式问题

    网页导出成word文档的默认视图方式问题 一般保存后的word文档默认是“Web版式视图”打开,这样会给客户的感觉不是真正的word文档,必须实现打开就是“页面视图” 1. 修改<html> ...

随机推荐

  1. Visual Studio 2013无法打开IIS Express Web的解决办法

    1. 首先参考了http://www.cr173.com/html/33412_1.html 2. 参考其最后,从微软官网下载安装WebMatrix,打开WebMatrix. 3. Visual St ...

  2. 2659: [Beijing wc2012]算不出的算式 - BZOJ

    最近有点颓废,刷水题,数学题(根本不会做啊) 题意:求 q,p是两个奇质数 网上题解就直接说是几何意义,问了别人才知道 我们在坐标轴上画出来就是在线段y=(q/p)x下方的格点和y=(p/q)x下方的 ...

  3. 一个有趣的 SQL 查询(查询7天连续登陆)

    一个有趣的 SQL 查询 一个朋友有这样一个SQL查询需求: 有一个登录表(tmp_test),包含用户ID(uid)和登录时间(login_time).表结构如下: . row ********** ...

  4. HDU 5629 Clarke and tree dp+prufer序列

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=562 题意: 求给每个节点的度数允许的最大值,让你求k个节点能组成的不同的生成树个数. 题解: 对于n ...

  5. [转载]MongoDB 标准连接字符串

    MongoDB 标准连接字符串 mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[data ...

  6. tangent space /handness

    normal tangent bitangent 三者互相垂直. 组成一个tangent space 表示一个点 对于原本位置的偏移(扰动) 考虑到这是为了 normalmap做出虚假的normal来 ...

  7. Eclipse下PHP开发 插件安装

    PHPeclipse是什么? PHPeclipse是Eclipse的一个插件,它为php开发人员提供了一个集成的开发环境.Eclipse官方下载地址:http://www.eclipse.org/ P ...

  8. SSH Tunneling Explained

    转载: http://chamibuddhika.wordpress.com/2012/03/21/ssh-tunnelling-explained/ March 21, 2012 by Buddhi ...

  9. poj 3268 Silver Cow Party(最短路,正反两次,这个模版好)

    题目 Dijkstra,正反两次最短路,求两次和最大的. #define _CRT_SECURE_NO_WARNINGS //这是找出最短路加最短路中最长的来回程 //也就是正反两次最短路相加找最大的 ...

  10. **CI两种方式查询所返回的结果数量

    区别:第一个是有条件的:第二个没有条件 $this->db->count_all_results(); 允许你获得某个特定的Active Record查询所返回的结果数量.可以使用Acti ...