asp.net大数据导出execl实现分开压缩并下载

/// <summary>
/// 导出数据到EXCEL 多个表的
/// </summary>
/// <param name="ds">数据集</param>
/// <param name="AbosultedFilePath">导出的 EXCEL 路径</param>
/// <param name="name">EXCEL 工作簿的名字</param>
/// <param name="title">表头</param>
/// <returns>返回文件路径</returns>
public static string ExportToExcels(System.Data.DataSet
ds, string AbosultedFilePath, string[]
name, string title)
{
try
{
string path
= ConfigHelper.GetValue("execlFile");
//判断路径是否存在
if (Directory.Exists(path))
{
//删除文件夹及文件
foreach (string d in Directory.GetFileSystemEntries(path))
{
if (File.Exists(d))
{
File.Delete(d); }
}
ectory.Delete(path, true);
Di
r
}
int PageIndex
= ;
if (ds.Tables.Count
<= )
return string.Empty;
for (int t
= ; t < ds.Tables.Count; t++)
{
System.Data.DataTable
dt = ds.Tables[t];
int count = dt.Rows.Count;//获取datatable内数据量
int pagecount = ; //每页的数据
PageIndex = Pagount(count, pagecount); //获取分页数
string filename
= t.ToString()
== "" ? "Area_Statistics" : "IP_statistics";
//存在分页时 创建新目录保存新execl文件
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
for (int i
= ; i <= PageIndex; i++)
{
//将模板文件复制到新目录下
string fileName
= path + "/" + filename + i + ".xls";
//根据页码获取DataTable内的数据
System.Data.DataTable
execlDT = GetPagedTable(dt, i, pagecount);
//将DataTable内的数据写入execl
RenderDataTableToExcel(execlDT,
fileName);
} }
//完成写入后 压缩文件
ZipDir(path,
path, , title);
return path
+ title + ".zip";
}
catch (Exception
ex)
{
Logger.Error("DataTable转execl失败" + ex.Message);
return string.Empty;
}
}
#region 压缩文件
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="DirToZip">文件夹路径</param>
/// <param name="ZipedFile">输出文件路径</param>
/// <param name="CompressionLevel">设置缓存大小</param>
///<param name="fileName">压缩后的文件名称</param>
public static void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel, string fileName)
{
try
{
//压缩文件为空时默认与压缩文件夹同一级目录
if (ZipedFile
== string.Empty)
{
ZipedFile =
DirToZip.Substring(DirToZip.LastIndexOf("\\") + );
ZipedFile =
DirToZip.Substring(, DirToZip.LastIndexOf("\\"))
+ "\\" + ZipedFile + ".zip";
}
if (System.IO.Path.GetExtension(ZipedFile)
!= ".zip")
{
ZipedFile =
ZipedFile + fileName + ".zip";
}
using (ZipOutputStream
zipoutputstream
= new ZipOutputStream(System.IO.File.Create(ZipedFile)))
{
zipoutputstream.SetLevel(CompressionLevel);
Crc32
crc = new Crc32();
System.IO.DirectoryInfo
myDir = new DirectoryInfo(DirToZip);
List<DictionaryEntry>
fileList = GetAllFiles(DirToZip);
foreach (DictionaryEntry
item in fileList)
{
//可能存在文件夹无法访问情况 需捕捉异常,根据实际情况返回
try
{
System.IO.FileStream
fs = System.IO.File.OpenRead(item.Key.ToString());
byte[]
buffer = new byte[fs.Length];
fs.Read(buffer, ,
buffer.Length);
ZipEntry
entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length
+ ));
entry.DateTime = (DateTime)item.Value;
entry.Size = fs.Length;
fs.Flush();
fs.Close();
crc.Update(
crc.Reset()
;buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, ,
buffer.Length);
}
catch (Exception
ex)
{
Logger.Error("压缩文件夹:" + ex.Message);
}
}
}
}
catch (Exception
ex)
{
Logger.Error("压缩execl文件夹:" + ex.Message);
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
private static List<DictionaryEntry>
GetAllFiles(string dir)
{
try
{
List<DictionaryEntry>
dictonary = new List<DictionaryEntry>();
if (!System.IO.Directory.Exists(dir))
{
return dictonary;
}
else
{
System.IO.DirectoryInfo
root = new System.IO.DirectoryInfo(dir);
System.IO.FileSystemInfo[]
arrary = root.GetFileSystemInfos();
for (int i
= ; i < arrary.Length; i++)
{
dictonary.Add(new DictionaryEntry(arrary[i].FullName,
arrary[i].LastWriteTime));
} }
return dictonary;
}
catch (Exception
ex)
{
Logger.Error("获取文件夹下的所有文件" + ex.Message);
return null;
}
}
#endregion #region DataTable分页
/// <summary>
/// DataTable分页
/// </summary>
/// <param
name="dt">DataTable</param>
/// <param name="PageIndex">页索引,注意:从1开始</param>
/// <param name="PageSize">每页大小</param>
/// <returns>分好页的DataTable数据</returns> 第1页 每页10条
public static System.Data.DataTable
GetPagedTable(System.Data.DataTable
dt, int PageIndex, int PageSize)
{
if (PageIndex
== ) { return dt; }
System.Data.DataTable
newdt = dt.Copy();
newdt.Clear();
int rowbegin
= (PageIndex - ) * PageSize;
int rowend
= PageIndex * PageSize;
if (rowbegin
>= dt.Rows.Count)
{ return newdt;
}
if (rowend
> dt.Rows.Count)
{
rowend = dt.Rows.Count; }
for (int i
= rowbegin; i <= rowend - ; i++)
{
DataRow
newdr = newdt.NewRow();
DataRow
dr = dt.Rows[i];
foreach (DataColumn
column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
wdt.Rows.Add(newdr);
}
n
e return newdt;
}
/// <summary>
/// 返回分页的页数
/// </summary>
/// <param name="count">总条数</param>
/// <param name="pageye">每页显示多少条</param>
/// <returns>如果 结尾为0:则返回1</returns>
public static int Pagount(int count, int pageye)
{
int page
= ;
int sesepage
= pageye;
if (count
% sesepage == ) { page = count / sesepage; }
else {
page = (count / sesepage) + ; }
if (page
== ) { page += ; }
return page;
}
#endregion
#region Datatable转Execl
/// <summary>
/// 把Datatable中的数据保存成指定的Excel文件
/// </summary>
/// <param name="SourceTable">需要转成execl的DateTable</param>
/// <param name="FileName">详细的文件路径带文件名与格式</param>
public static void RenderDataTableToExcel(System.Data.DataTable
SourceTable, string FileName)
{
Logger.Info("进入方法RenderDataTableToExcel 文件名:" + FileName);
HSSFWorkbook
workbook = new HSSFWorkbook();
MemoryStream
_ms = new MemoryStream();
// 创建Excel文件的Sheet
Sheet
sheet = workbook.CreateSheet("Sheet1");
sheet.SetColumnWidth(, * ); //设置单元格的宽度
sheet.SetColumnWidth(, * );//设置单元格的宽度
sheet.SetColumnWidth(, * );//设置单元格的宽度
// 创建行
Row
headerRow = sheet.CreateRow();
// 把Datatable中的列名添加Sheet中第一列中作为表头
foreach (DataColumn
column in SourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
int rowIndex
= ;
// 循环Datatable中的行和列添加数据到Excel中
foreach (DataRow
row in SourceTable.Rows)
{
Row
dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn
column in SourceTable.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
try
{
MemoryStream
ms = _ms as MemoryStream;
workbook.Write(ms);
_ms.Flush();
= ;
_ms.Position
FileStream
fs = new FileStream(FileName, FileMode.Create,
FileAccess.ReadWrite);
byte[]
data = ms.ToArray();
fs.Write(data, ,
data.Length);
fs.Flush();
fs.Close();
ms.Close();
ms.Flush();
data = null;
ms = null;
fs = null;
}
catch (Exception
ex)
{
Logger.Error("把Datatable中的数据保存成指定的Excel文件:" + ex.Message);
}
}
#endregion

然后是页面调用

string filepath = ExcelHelper.ExportToExcels(ds, ExcelBankPath, names, proName);
//判断返回的路径是否为空
if (!string.IsNullOrEmpty(filepath))
{
System.IO.FileInfo file = new System.IO.FileInfo(filepath);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
string fileName = "IPStatistics_" + DateTime.Now.ToString("yyMMdd") + new Random().Next(, ) + ExcelVersion;
//下载文件默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName + ".zip"));
//添加头信息,指定文件大小,让浏览器能显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/rar";
//把文件发送该客户段
Response.WriteFile(file.FullName);
}

asp.net大数据导出execl实现分开压缩并下载的更多相关文章

  1. Winform数据导出Execl小工具

    前台界面.cs文件 using System; using System.Collections.Generic; using System.ComponentModel; using System. ...

  2. asp.net将数据导出到excel

    本次应用datatable导出,若用gridview(假设gridview设为了分页显示)会出现只导出当前页的情况. protected void btnPrn_Click(object sender ...

  3. cloudera cdh6.3 离线安装 经典大数据平台视频教程(含网盘下载地址)

    cdh6.3企业级大数据视频教程 链接:https://pan.baidu.com/s/1bLGrIwzpFQB-pQRb6KOmNg 提取码:i8h8 系统和软件版本1,操作系统:Centos7.6 ...

  4. 大数据之路week06--day01(VMware的下载与安装、安装CentOS)

    好了,从今天开始就开始正式的进入大数据道路的轨道上了,当然了,Java 也是需要不断地在日后进行反复地学习,熟练掌握.(这里我要说一下,Java种还有一些I/O流.Lambda表达式和一些常用工具类有 ...

  5. asp.net C#数据导出Excel实例介绍

    excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用. Excel知识点. 一.添加引用和命名空间 添加Microsoft.Office.Interop.Excel引用,它 ...

  6. PHP处理大数据导出Excel方法

    在日常的工作中,很多时候都需要导出各种各样的报表,但是如果导出的数据一旦比较大,很容易就导致超时,对于这种问题,有很多的解决方法,例如网上说的分批导出.采用CSV.还有就采用JAVA.甚至是C++和C ...

  7. asp.net 把数据导出为excel

    本篇介绍c#中如何使用DataTable导出Excel,至于其他的导出方法,这里不作介绍! 1.首页从数据库读取数据,得到DataTable: DataTable dt = HelperExecute ...

  8. mysql大数据导出导入

    1)导出 select * from users into outfile '/tmp/users.txt';或 select * from users where sex=1 into outfil ...

  9. asp.net DataSet数据导出到Excel中

    方法: [STAThread]///这是必须的    public override void VerifyRenderingInServerForm(System.Web.UI.Control co ...

随机推荐

  1. PostgreSQL源代码中插件的使用

    如果编译数据库时使用了gmake world和gmake install-world, 所有的插件都会被安装, 那么就不需要再次安装了. 插件目录 contrib 进入要安装的插件目录, 例如 cd ...

  2. 阿里云安装mysql数据库出现2002错误解决办法

    在安装数据库的时候出现了如下错误: 解决办法如下: 1.在bin目录下 输入:kill -s 9 9907 再输入:ps -ef|grep mysql 显示如下: 2.回到lampp目录下,重启数据库 ...

  3. Map<String,String>转换json字符串

    import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class testJson ...

  4. php八大设计模式之简介篇

    设计模式的在面向对象中的重要性?       更深入的理解面向对象的思想,有利于开发出扩展性强的程序.在 PHP 面向对象中有一个 "开闭原则" :"软件实体应当对扩展开 ...

  5. 今日SGU 5.28

    SGU 121 题意:给你一张图,问你每个顶点必须有黑白两条边(如果它的边数>=2),问你怎么染色,不行就输出no 收获:你会发现不行的情况只有一个单纯的奇数环的时候,反之我们交替染色即可 #i ...

  6. docker安装cloudera manager,切换cloudera-scm用户报错can not open session

    在root帐号下su - cloudera-scm报错can not open session 在网上搜,大概是说ulimit超过限制之类,搞了很久才找到/etc/security/limits.d/ ...

  7. vim插件之delimitMate.vim

    delimitMate.vim--这个插件主要是在插入模式下,用来自动补全括号.引号等 下载地址 http://www.vim.org/scripts/script.php?script_id=275 ...

  8. CentOS7 启动[root@localhost ~]# systemctl start docker Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for de

    1).在linux虚拟机上安装docker步骤:1.检查内核版本,必须是3.10及以上uname ‐r2.安装dockeryum install docker3.输入y确认安装4.启动docker[r ...

  9. BZOJ 1578 DP

    思路:裸的完全背包 //By SiriusRen #include <cstdio> #include <cstring> #include <algorithm> ...

  10. Python(四) 分支、循环、条件与枚举

    一.什么是表达式 表达式(Expression)是运算符(operator)和操作数(operand)所构成的序列 二.表达式的优先级 三.表达式优先级练习 优先级同级 从左往右计算 1 or 2 a ...