【ASP.NET】C# 将HTML中Table导出到Excel(TableToExcel)
首先,说下应用场景 就是,把页面呈现的Table 导出到Excel中。其中使用的原理是 前台使用ajax调用aspx后台,传递过去参数值,导出。使用的组件是NPOI。
前台调用:
<script type="text/javascript">
function toExcel() {
post("../TableToExcel.aspx", { act: 'tabletoexcel', html: $('#excelTable').html() });
}
function post(URL, PARAMS) {
var temp = document.createElement("form");
temp.action = URL;
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
}
</script>
HTML页面内容示例:
<div class="formbody" id="excelTable">
<div class="formtitle"><span>报告详情页</span></div>
<table style="width: 100%;" id="tableCriHead" runat="server">
<tr>
<td>TEST</td>
</tr> </table>
</div>
后台生成代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.HSSF.Util;
using System.Text.RegularExpressions;
using System.IO; namespaceDemo
{
public partial class TableToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string act = GetValue("act"); //toExcel.aspx?act=tabletoexcel&html=<table class="reportstable">..</table>
if (act == "tabletoexcel")
{
TableToExcelMethod();
}
}
public void TableToExcelMethod()
{
string tableHtml = Request.Form["html"]; //接受前台table 数值字符串
if (string.IsNullOrEmpty(tableHtml)) { return; } InitializeWorkbook();
HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1"); string rowContent = string.Empty;
MatchCollection rowCollection = Regex.Matches(tableHtml, @"<tr[^>]*>[\s\S]*?<\/tr>",
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对tr进行筛选 NPOI.SS.UserModel.IFont fontSubTitle = hssfworkbook.CreateFont();
fontSubTitle.Boldweight = ;//加粗 NPOI.SS.UserModel.IFont fontBody = hssfworkbook.CreateFont();
fontBody.Boldweight = ;//加粗 for (int i = ; i < rowCollection.Count; i++)
{
HSSFRow row = (HSSFRow)sheet1.CreateRow(i);
rowContent = rowCollection[i].Value; MatchCollection columnCollection = Regex.Matches(rowContent, @"<th[^>]*>[\s\S]*?<\/th>",
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
for (int td = ; td < columnCollection.Count; td++)
{
row.CreateCell(td).SetCellValue(HtmlToTxt(columnCollection[td].Value));
} columnCollection = Regex.Matches(rowContent, @"<td[^>]*>[\s\S]*?<\/td>",
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
for (int td = ; td < columnCollection.Count; td++)
{
row.CreateCell(td).SetCellValue(HtmlToTxt(columnCollection[td].Value));
}
}
WriteToFile();
downFile(ppath);
} static HSSFWorkbook hssfworkbook;
public string ppath; public void WriteToFile()
{
string year = DateTime.Now.Year.ToString();
ppath = HttpContext.Current.Server.MapPath(DateTime.Now.ToString("yyyyMMddmmss") + ".xls");
FileStream file = new FileStream(ppath, FileMode.Create);
hssfworkbook.Write(file);
file.Close();
} public void InitializeWorkbook()
{
hssfworkbook = new HSSFWorkbook();
////create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "company";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "xxx";
hssfworkbook.SummaryInformation = si;
} public void downFile(string ppath)
{
if (File.Exists(ppath))
{
Response.ClearHeaders();
Response.Clear();
Response.Expires = ;
Response.Buffer = true;
Response.AddHeader("Accept-Language", "zh-cn");
string name = System.IO.Path.GetFileName(ppath);
System.IO.FileStream files = new FileStream(ppath, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] byteFile = null;
if (files.Length == )
{
byteFile = new byte[];
}
else
{
byteFile = new byte[files.Length];
}
files.Read(byteFile, , (int)byteFile.Length);
files.Close();
File.Delete(files.Name);
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
Response.ContentType = "application/octet-stream;charset=gbk";
Response.BinaryWrite(byteFile);
Response.End();
}
} /// <summary>
/// POST/GET 参数获取
/// </summary>
/// <param name="context"></param>
/// <param name="name"></param>
/// <returns></returns>
private string GetValue(string name)
{
string result = ConvertToString(Request.QueryString[name], "");
if (string.IsNullOrEmpty(result))
{
result = ConvertToString(Request.Form[name], "");
}
return FilterSpecial(result);
} public static string ConvertToString(Object obj, string strDefault)
{
try
{
if (obj == null)
{
return strDefault;
}
return obj.ToString();
}
catch
{
}
return strDefault;
} /// <summary>
/// HTML转行成TEXT
/// </summary>
/// <param name="strHtml"></param>
/// <returns></returns>
public static string HtmlToTxt(string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
};
string newReg = aryReg[];
string strOutput = strHtml;
for (int i = ; i < aryReg.Length; i++)
{
Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, string.Empty);
}
strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput.Replace("\r\n", "");
return strOutput;
} /// <summary>
/// 过滤特殊字符
/// 如果字符串为空,直接返回。
/// </summary>
/// <param name="str">需要过滤的字符串</param>
/// <returns>过滤好的字符串</returns>
public static string FilterSpecial(string str)
{
if (str == "")
{
return str;
}
else
{
str = str.Replace("'", "");
str = str.Replace("<", "");
str = str.Replace(">", "");
str = str.Replace("%", "");
str = str.Replace("'delete", "");
str = str.Replace("''", "");
str = str.Replace("\"\"", "");
str = str.Replace(",", "");
str = str.Replace(".", "");
str = str.Replace(">=", "");
str = str.Replace("=<", "");
str = str.Replace("-", "");
str = str.Replace("_", "");
str = str.Replace(";", "");
str = str.Replace("||", "");
str = str.Replace("[", "");
str = str.Replace("]", "");
str = str.Replace("&", "");
str = str.Replace("#", "");
str = str.Replace("/", "");
str = str.Replace("-", "");
str = str.Replace("|", "");
str = str.Replace("?", "");
str = str.Replace(">?", "");
str = str.Replace("?<", "");
str = str.Replace(" ", "");
return str;
}
}
}
}
附上NPOI的DLL下载地址: 点 击 下 载
最后,整体来说能够导出table到excel,但是同时存在一个问题,就是 导出后没有table的样式。
【ASP.NET】C# 将HTML中Table导出到Excel(TableToExcel)的更多相关文章
- js将HTML中table导出到EXCEL word (只支持IE) 另用php 配合AJAX可以支持所有浏览器
转载请注明来源:https://www.cnblogs.com/hookjc/ <HTML> <HEAD> <title>WEB页面导出为EXC ...
- html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式
先上代码 <script type="text/javascript" language="javascript"> var idTmr; ...
- JS 导出网页中Table内容到excel
<html> <head> <script type="text/javascript" language="javascript" ...
- HTML Table导出为Excel的方法
HTML Table导出为Excel的方法: 直接上源码 <html> <head> <meta http-equiv="Content-Type" ...
- 使用js代码将HTML Table导出为Excel
使用js代码将HTML Table导出为Excel的方法: 直接上源码 <html> <head> <meta http-equiv="Content-Type ...
- Antd将Table导出为Excel
Antd将Table导出为Excel 在最近的项目中,需要把表格中的数据导出给财务进行统计,网上很多一键导出的按钮都没用.经过东拼西凑,最终搞定了导出,自己封装了组件. import { File } ...
- HTML table导出到Excel中的解决办法
第一部分:html+js 1.需要使用的表格数据(先不考虑动态生成的table) <table class="table tableStyles" id="tabl ...
- C# html的Table导出到Excel中
C#中导出Excel分为两大类.一类是Winform的,一类是Web.今天说的这一种是Web中的一种,把页面上的Table部分导出到Excel中. Table导出Excel,简单点说,分为以下几步: ...
- Web页中table导出到execl(带模板)
1.将excel另存为html,将其复制到aspx文件中 2.输出格式为excel InitData(); Response.Clear(); Response.Buffer = true; Resp ...
随机推荐
- 【初识——最大流】 hdu 1532 Drainage Ditches(最大流) USACO 93
最大流首次体验感受—— 什么是最大流呢? 从一个出发点(源点),走到一个目标点(汇点),途中可以经过若干条路,每条路有一个权值,表示这条路可以通过的最大流量. 最大流就是从源点到汇点,可以通过的最大流 ...
- 序列化、反序列化和transient关键字的作用
引言 将 Java 对象序列化为二进制文件的 Java 序列化技术是 Java 系列技术中一个较为重要的技术点,在大部分情况下,开发人员只需要了解被序列化的类需要实现 Serializable 接口, ...
- hdu 1166 敌兵布阵(线段树单点更新,区间查询)
题意:区间和 思路:线段树 #include<iostream> #include<stdio.h> using namespace std; #define MAXN 500 ...
- 软件工程个人项目-Word frequency program by11061167龚少波
(一)工程设计时间预计 1.代码编写:4小时 熟悉Visual studio 2012的使用 : 程序代码部分主要分为三个步骤: (1)主函数的构建,包括各种函数调用及输入输出部分: (2)对目标文件 ...
- excel导入数据到sqlserver
1.读取excel数据到dataset public static System.Data.DataSet ExcelSqlConnection(string filepath, string tab ...
- PHP获取本周开始时间
/*先设置时区*/date_default_timezone_set('PRC');/*网上的写法:总觉得这周跨年或者跨月的时候会悲剧 未验证*/echo mktime(0,0,0,date('m') ...
- hadoop2.5.2学习及实践笔记(二)—— 编译源代码及导入源码至eclipse
生产环境中hadoop一般会选择64位版本,官方下载的hadoop安装包中的native库是32位的,因此运行64位版本时,需要自己编译64位的native库,并替换掉自带native库. 源码包下的 ...
- js 发红包
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...
- Docker 入门教程(转)
add by zhj: 可以简单的认为docker是对LXC(Linux Container)封装,它提供一种比LXC高级的API.Docker使用Go语言开发,利用了Linux提供的LXC,AUFS ...
- Struts Hello World Example
In this tutorial we show you how to develop a hello world web application using classic Struts 1.3 f ...