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. CUDA笔记(八)

    今天真正进入了攻坚期.不光是疲劳,主要是遇到的问题指数级上升,都是需要绕道的. 以visual profile来说,刚刚发现自己还没使用过. http://bbs.csdn.net/topics/39 ...

  2. Java 调用对象方法的执行过程

    弄清调用对象方法的执行过程十分重要.下面是调用过程的详细描述: 1) 编译器查看对象的声明类型和方法名.假设调用x.f(param),且隐式参数x声明为C类的对象.需要注意的是:有可能存在多个名为f, ...

  3. javascript实现多线程 Concurrent.Thread.js

    在这次我的项目中,因为前端要检测硬件加载并识别,再向后台请求发送数据,然后再返回的相应的配置文件!在这过程,要好时好几秒钟,严重影响体验效果,所以在网上靠看的方案,运用多线程去处理,这效果明显改善! ...

  4. TP5 上传文件

    直接贴上一个完整的代码 /** * 图片上传方法 * @return [type] [description] */ /** * 1 获取到文件 * 2 验证文件的形状是不是符合上传的规则 * 3 i ...

  5. Vector源码学习

    安全的可增长数组结构 实现: 1. 内部采用数组的方式. 1.1 添加元素,会每次校验容量是否满足, 扩容规则有两种,1.增加扩容补偿的长度,2.按照现有数组长度翻一倍.容量上限是Integer.MA ...

  6. 常见bug分析

    变量类型不匹配,形参和实参类型不匹配,隐式类型转换,变量类型赋值不匹配, 工具不熟悉,导致逻辑错误,查看代码,测试驱动开发,完整的测试用例,覆盖所有分支, 变量超出范围,对于大的数据要特别注意, 工具 ...

  7. uname---用于打印当前系统相关信息

    uname命令用于打印当前系统相关信息(内核版本号.硬件架构.主机名称和操作系统类型等). 语法 uname(选项) 选项 -a或--all:显示全部的信息: -m或--machine:显示电脑类型: ...

  8. Python组织文件 实践:将带有美国风格日期的文件改名为欧洲风格日期

    描述:假设有这样一个任务,你需要将文件名中含有美国风格日期(MM-DD-YYYY)的部分更换为欧洲风格日期(DD-MM-YYYY),并且需要你处理的文件多达上千个 分析:检查当前工作目录的所有文件名, ...

  9. Unity Shader (四)片段程序示例

      1.环境光+漫反射+高光+点光源 Shader "Custom/Example_Frag_1" { properties { _MainColor(,,,) _Specular ...

  10. 转:Mac下搭建svn服务器和XCode配置svn

    Mac下搭建svn服务器和XCode配置svn 先打开命令行终端. 1.创建svn repository svnadmin create /yourpath/svnroot/repository 2. ...