DataTable数据导出到Excel,并发送到客户端进行下载
本代码实现思路是:页面显示和导出分开,导出的数据和用于页面显示的是同一查询数据方式,所以也是同样的数据,只是在导出数据时从数据库重新捞了一次数据。
此导出数据方式会先将数据保存到Excel中,然后将创建的Excel文件保存到服务器指定位置,然后下载到客户端,下载完后立即删除掉刚在服务器上创建的Excel文件。
// 导出按钮事件
protected void btOutputData_Click(object sender, EventArgs e)
{
ExportExcel(GetPrintingData(ViewState["ssearchCondition"].ToString()), Convert.ToInt32(ConfigurationManager.AppSettings["OutputData PageSize"].ToString()));
}
#region 导出数据
/// <summary>
/// 获取需要导出的数据
/// </summary>
/// <param name="strWhere">筛选数据的条件</param>
/// <returns></returns>
public System.Data.DataTable GetPrintingData(string strWhere)
{
System.Data.DataTable dt = GetListByPage(strWhere, , GetRecordCount(ViewState["ssearchCondition"].ToString()));
System.Data.DataTable newTable = new System.Data.DataTable();
newTable.Columns.AddRange(new DataColumn[]{
new DataColumn("rowN"),
new DataColumn("Description"),
new DataColumn("area"),
new DataColumn("projectName"),
new DataColumn("stake"), new DataColumn("itemProjectName"),
new DataColumn("newCol2"),
new DataColumn("newCol3"),
new DataColumn("newCol4"),
new DataColumn("newCol5"), new DataColumn("newCol6"),
new DataColumn("newCol7"),
new DataColumn("acceptConclution_zdb"),
new DataColumn("newCol8"),
new DataColumn("acceptConclution_zjb"), new DataColumn("joinAccept_yz"),
new DataColumn("joinAccept_zjb"),
new DataColumn("joinAccept_zdb"),
new DataColumn("joinAccept_xmb")});
int num = ;
for (int i = ; i < dt.Rows.Count; i++)
{
DataRow newRow = newTable.NewRow();
newRow["rowN"] = num++;// dt.Rows[i]["rowN"];
newRow["Description"] = dt.Rows[i]["Description"];
newRow["area"] = dt.Rows[i]["area"];
newRow["projectName"] = dt.Rows[i]["projectName"];
newRow["stake"] = dt.Rows[i]["stake"]; newRow["itemProjectName"] = dt.Rows[i]["itemProjectName"];
newRow["newCol2"] = dt.Rows[i]["newCol2"];
newRow["newCol3"] = dt.Rows[i]["newCol3"];
newRow["newCol4"] = dt.Rows[i]["newCol4"];
newRow["newCol5"] = dt.Rows[i]["newCol5"]; newRow["newCol6"] = dt.Rows[i]["newCol6"];
newRow["newCol7"] = dt.Rows[i]["newCol7"];
newRow["acceptConclution_zdb"] = dt.Rows[i]["acceptConclution_zdb"];
newRow["newCol8"] = dt.Rows[i]["newCol8"];
newRow["acceptConclution_zjb"] = dt.Rows[i]["acceptConclution_zjb"]; newRow["joinAccept_yz"] = dt.Rows[i]["joinAccept_yz"];
newRow["joinAccept_zjb"] = dt.Rows[i]["joinAccept_zjb"];
newRow["joinAccept_zdb"] = dt.Rows[i]["joinAccept_zdb"];
newRow["joinAccept_xmb"] = dt.Rows[i]["joinAccept_xmb"];
newTable.Rows.Add(newRow);
}
return newTable;
}
/// <summary>
/// 把table中的数据导出到excel中去
/// </summary>
/// <param name="dt">要导入的table</param>
/// <param name="maxcount">模板excel中,一个sheet要显示的行数,如果数据多一个sheet中的最大值,会自动生成新的sheet</param>
private void ExportExcel(System.Data.DataTable dt, int maxcount)
{
Random ran = new Random();
string fileautoname = Server.MapPath("~/") + DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(, ) + ".xls";//给新文件命名
string filepath = Server.MapPath("/") + "UpLoadFile\\Template\\OutputDataBlock.xls"; //模板文件路径
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.Application application = new Application();
Workbook workbook = application.Workbooks.Open(filepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Worksheet worksheet;
worksheet = (Worksheet)workbook.Sheets.get_Item();
//DataView dv = dt.DefaultView;
//dv.Sort = "id asc"; //table 中的数据按id升序排列
//System.Data.DataTable table = dv.ToTable();
System.Data.DataTable table = dt;
int sheetcount = GetSheetCount(table.Rows.Count, maxcount);
for (int count = ; count < sheetcount; count++)
{
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(count)).Copy(missing, workbook.Worksheets[count]);
}
List<object[,]> list = new List<object[,]>();
object[,] ret;
for (int count = ; count < sheetcount; count++)
{
if (count == sheetcount - )
{
ret = new object[table.Rows.Count - count * maxcount, table.Columns.Count - ];
for (int i = ; i < table.Rows.Count - count * maxcount; i++)
{
for (int j = ; j < table.Columns.Count - ; j++)
{
ret[i, j] = table.Rows[count * maxcount + i][j];
}
}
list.Add(ret);
}
else
{
ret = new object[maxcount, table.Columns.Count - ];
for (int i = ; i < maxcount; i++)
{
for (int j = ; j < table.Columns.Count - ; j++)
{
ret[i, j] = table.Rows[i + count * maxcount][j];
}
}
list.Add(ret);
}
} object[,] obj;
for (int p = ; p < list.Count; p++)
{
worksheet = (Worksheet)workbook.Sheets.get_Item(p + );
obj = list[p];
string cn = "L" + (obj.GetLength() + ).ToString(); //设置填充区域
worksheet.get_Range("A3", cn).FormulaR1C1 = obj;
}
workbook.SaveAs(fileautoname, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
workbook.Close(missing, missing, missing);
application.Quit();
workbook = null; #region
System.IO.FileInfo file = new System.IO.FileInfo(fileautoname);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString()); // 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel"; // 把文件流发送到客户端
Response.WriteFile(file.FullName);
Response.Flush();//这个语句必须有,否则就不回弹出保存的对话框,搞了N久 //删除长生的临时Excel文件
string filePath = fileautoname;//获取文件路径
if (filePath != null && System.IO.File.Exists(filepath))
{
//判断文件是否存在,如果存在,就删除之
System.IO.File.Delete(filePath);
} // 停止页面的执行
Response.End();
#endregion
}
/// <summary>
/// 获取WorkSheet数量
/// </summary>
/// <param name="rowCount">记录总行数</param>
/// <param name="rows">每WorkSheet行数</param>
/// <returns></returns>
private int GetSheetCount(int rowCount, int rows)
{
int n = rowCount % rows; //余数 if (n == )
return rowCount / rows;
else
return Convert.ToInt32(rowCount / rows) + ;
} #endregion
DataTable数据导出到Excel,并发送到客户端进行下载的更多相关文章
- C#将DataTable数据导出到EXCEL的两种方法
1.在非服务器控件的页面导出数据,需要借助一张temp空页面post回后台的数据. 前台:window.location.href = "../Temp.aspx"; 后台: tr ...
- C# CLosedXML四句代码搞定DataTable数据导出到Excel
最近用到DataTable导出到Excel,网上看了一下,都不怎么好使,逛了下GitHub一下完美解决了 用到的.net库CLosedXML,这个库用于读取,处理和写入Excel 2007+(.xls ...
- 将IList、DataTable数据导出到Excel
/// <summary> /// IList导出Excel /// </summary> /// <typeparam name="T">&l ...
- C# 获取DataTable数据导出到Excel
protected void ExportExcel(System.Data.DataTable dt) { ) return; Microsoft.Office.Interop.Excel.Appl ...
- 利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。
正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的‘好’东西记 ...
- 在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。
正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记 ...
- C#大量数据导出到Excel(转)
工作过程中经常会用到将数据导出到Excel中,一般情况下需要导出的数据都是几百几千条或者上万条,这都没有什么问题,但有时候会遇到特殊的需求,客户要求把几十万条甚至上百万条的数据导出到Excel中,这就 ...
- Excel催化剂开源第15波-VSTO开发之DataTable数据导出至单元格区域
上篇提到如何从Excel界面上拿到用户的数据,另外反方向的怎样输出给用户数据,也是关键之处. VSTO最大的优势是,这双向的过程中,全程有用户的交互操作. 而一般IT型的程序,都是脱离用户的操作,只能 ...
- 将C1Chart数据导出到Excel
大多数情况下,当我们说将图表导出到Excel时,意思是将Chart当成图片导出到Excel中.如果是这样,你可以参考帮助文档中保存和导出C1Chart章节. 不过,也有另一种情况,当你想把图表中的数据 ...
随机推荐
- Linux学习笔记 (四)归档和压缩
一.zip压缩命令: 1.压缩文件: 格式:zip 压缩文件 源文件 例:zip abc.zip abc //将abc文件压缩到abc.zip文件内. 2.压缩目录: 格式:zip –r 压缩目录 ...
- Objective-C学习笔记(二十一)——函数的返回值与參数类型
我们在之前的博客中涉及到的函数都没有參数,同一时候返回值也为void,即不须要返回值. 可是在以后的开发中.函数返回值和參数是必须涉及到的. 所以如今我们来讨论这个问题.我们还是以People类为例. ...
- iOS 之UIBezierPath
代码地址如下:http://www.demodashi.com/demo/11602.html 在之前的文章中,由于用到过UIBezierPath这个类,所以这里就对这个类进行简单的记录一下,方便自己 ...
- lucene 异常 Lock obtain timed out 解决方法
http://terje.blog.163.com/blog/static/119243712008102122316595/ 一般都是索引建立的过程中,不正常操作影响了IndexWriter ...
- spring揭秘读书笔记----spring的ioc容器之BeanFactory
spring的ioc容器是一种特殊的Ioc Service Provider(ioc服务提供者),如果把普通的ioc容器认为是工厂模式(其实很相似),那spring的ioc容器只是让这个工厂的功能更强 ...
- webpack打包vue2.0项目时必现问题(转载)
原文地址:http://www.imooc.com/article/17868 [Vue warn]: You are using the runtime-only build of Vue wher ...
- Go环境IDE安装配置
终于配好了自己的Go环境,每天可以来一点积累了. MAC安装配置过程参考了如下几个博文~谢谢 Intellij安装配置: http://blog.csdn.net/fenglailea/article ...
- 谈谈varnish,squid,apache,nginx缓存的对比
总是有人在问cache用什么,有varnish,squid,apache,nginx这几种,到底是我们用什么架构cache. 1.从这些功能上.varnish和squid是专业的cache服务,而ap ...
- iOSXib布局后代码修改约束的值
如何修改autolayout 约束的值? 目前我已知的方法有5种 1.修改frame(有时候可能会不起作用,但可以做动画) 2.修改约束的float值 3.使用VisualFormat 语言 4. ...
- Harmonic Number 求Hn; Hn = 1 + 1/2 + 1/3 + ... + 1/n; (n<=1e8) T<=1e4; 精确到1e-8; 打表或者调和级数
/** 题目:Harmonic Number 链接:https://vjudge.net/contest/154246#problem/I 题意:求Hn: Hn = 1 + 1/2 + 1/3 + . ...