您的位置:首页 > 理论基础 > 计算机网络

ASP.Net MVC中数据库数据导出Excel,供HTTP下载(转)

2014-03-20 11:30 555 查看
[code] <connectionStrings>

<add name="TestConnectionString" connectionString="Data Source=(local);Initial Catalog=Test;Integrated Security=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

[/code]
[/code]

通过以上几步,我们已经建立了基本环境,下面我们来中点介绍下NPOI和FileResult的使用:

1.写NPOI导出方法,首先必须using命名空间NPOI.SS.UserModel和NPOI.HSSF.UserModel。在这个例子中,NPOI将输入DataSet对象,转化为Excel表格,并且保存了MemoryStream的内存流对象,这样做的好处:在提供下载的同时,不会在服务器端产生中间文件。

这里采用的是以基于Column和Row的方式解析Dataset对象的。

[code]
[code] using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

using NPOI.SS.UserModel;

using NPOI.HSSF.UserModel;

using System.Data;


namespace SQLServer2Excel.Models

{

 public class ExportTool

{

 /// <summary>

 /// 将DataSet数据集转换HSSFworkbook对象,并保存为Stream流

 /// </summary>

 /// <param name="ds"></param>

 /// <returns>返回数据流Stream对象</returns>

 public static MemoryStream ExportDatasetToExcel(DataSet ds)

{

 try

{

 //文件流对象

MemoryStream stream = new MemoryStream();


 //打开Excel对象

 HSSFWorkbook workbook = new HSSFWorkbook();


 //Excel的Sheet对象

 NPOI.SS.UserModel.Sheet sheet = workbook.CreateSheet("sheet1");


 //set date format

 CellStyle cellStyleDate = workbook.CreateCellStyle();

 DataFormat format = workbook.CreateDataFormat();

 cellStyleDate.DataFormat = format.GetFormat("yyyy年m月d日");


 //使用NPOI操作Excel表

 NPOI.SS.UserModel.Row row = sheet.CreateRow(0);

 int count = 0;

 for (int i = 0; i < ds.Tables[0].Columns.Count; i++) //生成sheet第一行列名 

{

 NPOI.SS.UserModel.Cell cell = row.CreateCell(count++);

 cell.SetCellValue(ds.Tables[0].Columns[i].Caption);

}

 //将数据导入到excel表中

 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

{

 NPOI.SS.UserModel.Row rows = sheet.CreateRow(i + 1);

 count = 0;

 for (int j = 0; j < ds.Tables[0].Columns.Count; j++)

{

 NPOI.SS.UserModel.Cell cell = rows.CreateCell(count++);

 Type type = ds.Tables[0].Rows[i][j].GetType();

 if (type == typeof(int) || type == typeof(Int16)

 || type == typeof(Int32) || type == typeof(Int64))

{

 cell.SetCellValue((int)ds.Tables[0].Rows[i][j]);

}

 else

{

 if (type == typeof(float) || type == typeof(double) || type == typeof(Double))

{

 cell.SetCellValue((Double)ds.Tables[0].Rows[i][j]);

}

 else

{

 if (type == typeof(DateTime))

{

 cell.SetCellValue(((DateTime)ds.Tables[0].Rows[i][j]).ToString("yyyy-MM-dd HH:mm"));

}

 else

{

 if (type == typeof(bool) || type == typeof(Boolean))

{

 cell.SetCellValue((bool)ds.Tables[0].Rows[i][j]);

}

 else

{

 cell.SetCellValue(ds.Tables[0].Rows[i][j].ToString());

}

}

}

}

}

}


 //保存excel文档

 sheet.ForceFormulaRecalculation = true;


 workbook.Write(stream);

 workbook.Dispose();


 return stream;

}

 catch

{

 return new MemoryStream();

}

}

}

}

[/code]
[/code]

2. FileResult的使用,这里实际上用到的是其之类FileStreamResult。

[code]
[code] public FileResult DownloadFile()

{

 DataSet ds = Person.GetPersonDataSet(new DataSet());


 MemoryStream stream = ExportTool.ExportDatasetToExcel(ds);

 stream.Seek(0, SeekOrigin.Begin);


 return File(stream, "application/vnd.ms-excel", "spreadsheet1.xls");

}

[/code]
[/code]
这里说明一下两点: a. 第6行代码的作用:如果没有这行代码,可能保存的数据大小为0kb,这是因为调整下输出流的开始位置;
b.第8行File()方法,此方法的各种重载方法,可以返回FileResult的之类对象。在这里第二参数“application/vnd.ms-excel”代表Excel文件,第三个参数给定文件名。
[/quote]

最终效果图:


源码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: