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. Careercup - Facebook面试题 - 5179916190482432

    2014-05-01 00:45 题目链接 原题: input [,,,] output [,,,] Multiply all fields except it's own position. Res ...

  2. angular入门系列教程4

    主题: 本篇主要目的就是继续完善home页下的index子页面的内容,处理一个列表,进行增删改查过滤等操作. 效果图: 细节: 主要的更改有两个,一个是修改模板index.html,还有就是增加控制器 ...

  3. Eclipse 创建Maven工程

    前言 开发环境 sts-3.7.2.RELEASE 创建步骤 1.开启eclipse,右键new——>other,如下图找到maven project 2.选择maven project,显示创 ...

  4. 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

    // test14.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> #include< ...

  5. HDOJ 3547 DIY Cube 解题报告

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3547 题目大意:求用$C$种颜色给立方体的8个顶点染色的本质不同的方法.两种方法本质不同即不能通过旋转 ...

  6. Windows ftp 连不上Linux

    1.首先检查vsftpd服务器 是否安装 $ rpm -qa | grep vsftpdvsftpd-2.2.2-11.el6.x86_64 2.显示已安装,restart the vsftpd ¥ ...

  7. 解决ORA-00020错误

    解决ORA-00020错误 分类: Oracle2009-05-13 17:26 3398人阅读 评论(0) 收藏 举报 数据库sessionoraclesql服务器object 项目上使用的Orac ...

  8. 如何恢复SQL Server 中的Master库

    如何恢复SQL Server 2005中的Master库 2011-05-10 16:34 Vegas Lee 博客园 我要评论(0) 字号:T | T   master库对于SQLServer来说, ...

  9. php集成开发环境的安装以及Zend Studio开发工具的安装

    一.集成开发环境: wampserver 下载地址: 官网: http://www.wampserver.com/ 直接下载 http://sourceforge.net/projects/wamps ...

  10. hdu 1753 大明A+B

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1753 容易出错的事例: 0.1 0.2 1.88 22.22 1 0.01 大概出错的几个点,做久了思维根 ...