HTML页面导出为Word
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的更多相关文章
- aspx页面导出为word
aspx页面导出为word代码: System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWri ...
- (转)WEB页面导出为Word文档后分页&横向打印的方法
<html> <HEAD> <title>WEB页面导出为Word文档后分页&横向打印的方法 </title> < ...
- c# 将页面导出到word(含图片及控件)
/// <summary> /// 创建word /// <param name="filePath">文件路径 </param> /// &l ...
- PHP 将html页面导出至Word
<?php header("Content-Type: application/msword"); header("Content-Disposition: att ...
- 【MVC】 非常简单的页面导出 WORD, EXCEL方法
[MVC] 页面导出 WORD, EXCEL 前端 js function output() { var para = new Object(); para.html = getHtml(" ...
- Java 实现HTML富文本导出至word完美解决方案
一. 问题的提出 最近用java开发一个科技项目信息管理系统,里面有一个根据项目申请书的模板填写项目申报信息的功能,有一个科技项目申请书word导出功能. 已有的实现方式:采用标准的jsp模板输出实现 ...
- javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页
由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...
- 将HTML导出生成word文档
前言: 项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔. 当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下.下面就介绍两个导出word文档的方法. ...
- 网页导出成word文档的默认视图方式问题
网页导出成word文档的默认视图方式问题 一般保存后的word文档默认是“Web版式视图”打开,这样会给客户的感觉不是真正的word文档,必须实现打开就是“页面视图” 1. 修改<html> ...
随机推荐
- Snapchat
"Mesaging service Snapchat reportedly turned down a $3 billion offer from Facebook?!" Ever ...
- javascript中alert()与console.log()的区别
我们在做js调试的时候使用 alert 可以显示信息,调试程序,alert 弹出窗口会中断程序, 如果要在循环中显示信息,手点击关闭窗口都累死.而且 alert 显示对象永远显示为[object ]. ...
- Matlab与科学计算的基本运算
各种允许的比较关系 >, >=, <, <=, ==,~=, find(), all(), any() 例:>> A=[1,2,3;4,5,6;7,8,0]A = ...
- 有关javascript中的JSON.parse和JSON.stringify的使用一二
有没有想过,当我们的大后台只是扮演一个数据库的角色,json在前后台的数据交换中扮演极其重要的角色时,作为依托node的前端开发,其实相当多的时间都是在处理数据,准确地说就是在处理逻辑和数据(这周实习 ...
- iOS开发之深入探讨runtime机制01-类与对象
最近有个同事问我关于“runtime机制”的问题,我想可能很多人对这个都不是太清楚,在这里,和大家分享一下我对于runtime机制的理解.要深入理解runtime,首先要从最基本的类与对象开始,本文将 ...
- 翻译:AngularJS应用的认证技术
原文: https://medium.com/opinionated-angularjs/7bbf0346acec 认证 最常用的表单认证就是用户名(或者邮件)和密码登录.这就表示要实现一个用户可以输 ...
- POJ2752 Seek the Name,Seek the Fame KMP算法
KMP继续练手.题目问的是一个串前缀等于后缀的可能长度是哪些,输出来.题目考的是对KMP失配指针的理解,当最后一位失配(即'\0'那里)时,指针会移动到前缀对应匹配的部分,所以这个长度是我们要的,然后 ...
- TDD 用语
OOP 封装 继承 多态 SOLID SRP 单一职责 Single Responsibility Principle OCP 开放封闭 Open/Close Principle LS ...
- 搭建hadoop环境,在win7的eclipse上远程操作(Linux上)hadoop2.6.0出错的一些总结
问题1:在DFS Lcation 上不能对文件进行操作: 解决方法: 在hadoop上的每个节点上修改该文件 conf/mapred-site.xml,增加: <property> < ...
- lintcode:最大子数组差
题目 最大子数组差 给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大. 返回这个最大的差值. 样例 给出数组[1, 2, -3, 1], ...