asp.net大数据导出execl实现分开压缩并下载
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实现分开压缩并下载的更多相关文章
- Winform数据导出Execl小工具
前台界面.cs文件 using System; using System.Collections.Generic; using System.ComponentModel; using System. ...
- asp.net将数据导出到excel
本次应用datatable导出,若用gridview(假设gridview设为了分页显示)会出现只导出当前页的情况. protected void btnPrn_Click(object sender ...
- cloudera cdh6.3 离线安装 经典大数据平台视频教程(含网盘下载地址)
cdh6.3企业级大数据视频教程 链接:https://pan.baidu.com/s/1bLGrIwzpFQB-pQRb6KOmNg 提取码:i8h8 系统和软件版本1,操作系统:Centos7.6 ...
- 大数据之路week06--day01(VMware的下载与安装、安装CentOS)
好了,从今天开始就开始正式的进入大数据道路的轨道上了,当然了,Java 也是需要不断地在日后进行反复地学习,熟练掌握.(这里我要说一下,Java种还有一些I/O流.Lambda表达式和一些常用工具类有 ...
- asp.net C#数据导出Excel实例介绍
excel导出在C#代码中应用己经很广泛了,我这里就做些总结,供自己和读者学习用. Excel知识点. 一.添加引用和命名空间 添加Microsoft.Office.Interop.Excel引用,它 ...
- PHP处理大数据导出Excel方法
在日常的工作中,很多时候都需要导出各种各样的报表,但是如果导出的数据一旦比较大,很容易就导致超时,对于这种问题,有很多的解决方法,例如网上说的分批导出.采用CSV.还有就采用JAVA.甚至是C++和C ...
- asp.net 把数据导出为excel
本篇介绍c#中如何使用DataTable导出Excel,至于其他的导出方法,这里不作介绍! 1.首页从数据库读取数据,得到DataTable: DataTable dt = HelperExecute ...
- mysql大数据导出导入
1)导出 select * from users into outfile '/tmp/users.txt';或 select * from users where sex=1 into outfil ...
- asp.net DataSet数据导出到Excel中
方法: [STAThread]///这是必须的 public override void VerifyRenderingInServerForm(System.Web.UI.Control co ...
随机推荐
- cuda thrust函数首次调用耗费时间比后续调用长原因
lazy context initialisation. stackoverflow
- OGG切换步骤
步骤描述 提前准备好切换方案:以及其他相关人员的配合 切换至容灾数据库: (1)停止前端业务,确认目标端数据已经追平 (2)数据校验,确认数据一致 (3)停止生产库OGG进程(停止后可以直接删除) ( ...
- BZOJ 3277/3473 广义后缀自动机
说实话没啥难的. 建一棵广义后缀自动机,暴力自底向上更新即可. 时间复杂度非常玄学,但据说是可以过的. 要注意每个串中相同的子串的贡献是都要加进去的,开始因为这个被坑了好久 QAQ Code: #in ...
- 命令alias、gerp、find及基础Shell脚本
一. alias 命令:系统设置命令别名 用法:alias [-p] [name[=value] ... ] 注意‘=’和字符串之间不能包含空格 显示当前设置的别名:alias 或 alias ...
- [BJOI2018]求和(树链剖分)
题目描述 master 对树上的求和非常感兴趣.他生成了一棵有根树,并且希望多次询问这棵树上一段路径上所有节点深度的 kkk 次方和,而且每次的 kkk 可能是不同的.此处节点深度的定义是这个节点到根 ...
- 题解 P1179 【数字统计】
嚯嚯嚯,这道题很显然是削弱版的51nod P1042. 那么显然我们需要使用数位DP解题. 思路大致是这样的: 对于每一个数字,考虑三种影响关系: 1. 它对低位的影响 2. 它对高位的影响 3. 高 ...
- 【Henu ACM Round#19 E】 Om Nom and Candies
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 紫书上的原题: 链接 [代码] #include <bits/stdc++.h> #define ll long lon ...
- 【SRM 717 DIV2 C】DerangementsDiv2
Problem Statement You are given two ints: n and m. Let D be the number of permutations of the set {1 ...
- 用eclipse 检索SVN 上 myEclipse 建的web项后,成java项目解决方法
用eclipse 检索SVN 上 myEclipse 建的web项后,成java项目解决方法 在网上找了非常多,都无论用. 说添加.project 文件几个属性.但我发现里面都有,在我这里无论什么用. ...
- Mac上配置 Ruby on Rails和Git
Ruby on Rails on Mac =============================================================================== ...