项目中需要将页面中的table内容导出到EXCEL,在用了几种方法后发现NPO是最快&最好的

需要应用 NPOI.dll 还有个Ionic.Zip.dll不知道有用没,没去研究,两个DLL都放到bin目录里了

NPOIX dll点击下载

假设页面中有个<div id="excelTable"><table>.....</table></div>需要导出到EXCEL

在页面中加一个button

<input type="button" name="excelBut" value="导出Excel" onclick="toExcel()" class="sgbtn" /> 

页面任意部分插入一段javascript:

function toExcel()
{
post("tools/toExcel.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;
}
toExcel.aspx文件空白即可
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="toExcel.aspx.cs" Inherits="tools_toExcel" %>
toExcel.aspx.cs代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls; using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.HSSF.Util;
using System.Text.RegularExpressions;
using System.IO; public partial class tools_toExcel : 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")
{
TableToExcel();
}
} public void TableToExcel()
{
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 = 800;//加粗 NPOI.SS.UserModel.IFont fontBody = hssfworkbook.CreateFont();
fontBody.Boldweight = 500;//加粗 for (int i = 0; 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 = 0; td < columnCollection.Count; td++)
{
row.CreateCell(td).SetCellValue(StrTools.HtmlToTxt(columnCollection[td].Value));
} columnCollection = Regex.Matches(rowContent, @"<td[^>]*>[\s\S]*?<\/td>",
RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
for (int td = 0; td < columnCollection.Count; td++)
{
row.CreateCell(td).SetCellValue(StrTools.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 = 0;
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 == 0)
{
byteFile = new byte[1];
}
else
{
byteFile = new byte[files.Length];
}
files.Read(byteFile, 0, (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 = ConvertData.ConvertToString(Request.QueryString[name], "");
if (string.IsNullOrEmpty(result))
{
result = ConvertData.ConvertToString(Request.Form[name], "");
}
return StrTools.SafeSqlstr(result);
}
}

  这样就可以将HTML中的TABLE方便地导出EXCEL了~代码有点乱,别介意哈。

使用NPOI将TABLE内容导出到EXCEL的更多相关文章

  1. 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; ...

  2. JS 将Table内容导出到Excel(样式设计)

    转载请注明来源:https://www.cnblogs.com/hookjc/ function saveAsExcel(tableID){ var tb = new TableToExcel(tab ...

  3. jsp 页面内容导出到Excel中

    日常使用网络资源时经常需要把网页中的内容下载到本地,并且导出到Excel中,现在介绍一种非常简单的方式实现网络资源的下载.只需要讲jsp的最上面加上一句话 <% response.reset() ...

  4. 将页面上的内容导出到Excel

    <asp:Button ID="lkbExport" runat="server" Name="Save" Text="导出 ...

  5. html5中 table数据导出到excel文件

    JS代码: /** * table数据导出到excel * 形参 table : tableId ; * sheetName : 工作薄名 * fileName : 文件名 * linkId :隐藏的 ...

  6. 【WPF】将DataGrid内容导出到Excel

    引言 在做项目时要求将datagrid的内容导出到Excel,以前做winform项目时遇到过,就把代码搬过来用,但wpf和winform还是有些不同,就修改了一些东西,使其能实现这个功能. 本文是导 ...

  7. vue项目中的elementUI的table组件导出成excel表

    1.安装依赖:npm install --save xlsx file-saver 2.在放置需要导出功能的组件中引入 import FileSaver from 'file-saver' impor ...

  8. 纯JS 将table表格导出到excel

    html <div > <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv ...

  9. asp.net将内容导出到Excel,Table表格数据(html)导出EXCEL

    代码: /// <summary> /// HTML Table表格数据(html)导出EXCEL /// </summary> /// <param name=&quo ...

随机推荐

  1. Codeforces Round #341 (Div. 2)

    在家都变的懒惰了,好久没写题解了,补补CF 模拟 A - Wet Shark and Odd and Even #include <bits/stdc++.h> typedef long ...

  2. 链表 UVA 11988 Broken Keyboard (a.k.a. Beiju Text)

    题目传送门 题意:训练指南P244 分析:链表模拟,维护链表的head和tail指针 #include <bits/stdc++.h> using namespace std; const ...

  3. three.js入门3

    为什么要用three.js Three.js为我们封装了底层的WebGl接口,使我们在无需掌握繁冗的图形学知识的基础下可以轻松的创建三维场景.相比较使用底层的WebGL我们可以使用更少的代码,大大的降 ...

  4. 解决嵌入WinForm的WPF控件无法显示图片问题

    解决办法是在控件初始化时,通过下面方法再次加载图片: ucCanvas.CreateCoordinateImage.Source = GetImageIcon(global::MainApplicat ...

  5. BZOJ2149 : 拆迁队

    设$c[i]=g[i]+\frac{i(i+1)}{2}-a[i]\times i-a[i]$,$d[i]=a[i]-i$ $f[i]$表示以$i$为结尾最多保留多少个建筑,则 $f[i]=\max( ...

  6. DOM的概念及子节点类型

    前言 DOM的作用是将网页转为一个javascript对象,从而可以使用javascript对网页进行各种操作(比如增删内容).浏览器会根据DOM模型,将HTML文档解析成一系列的节点,再由这些节点组 ...

  7. CentOS6.4 安装nmon

    安装 mkdir /usr/local/nmon cd /usr/local/nmon wget http://sourceforge.net/projects/nmon/files/nmon_lin ...

  8. Codeforces Testing Round #10 B. Balancer

    水题,只要遍历一遍,不够平均数的,从后面的借,比平均数多的,把多余的数添加到后面即可,注意数据范围 #include <iostream> #include <vector> ...

  9. iframe高度自适应内容

    JS自适应高度,其实就是设置iframe的高度,使其等于内嵌网页的高度,从而看不出来滚动条和嵌套痕迹.对于用户体验和网站美观起着重要作用. 如果内容是固定的,那么我们可以通过CSS来给它直接定义一个高 ...

  10. vs2013的单元测试 第一部分

    这次的vs2013的单元测试我学到了许多,虽然到现在我还是不能完成,但是我也学到了许多. 首先,在vs2013中先安装Unit Test Generator,如图所示: 这个是进行单元测试重要的一个插 ...