首先要引用dll

下载地址:http://pan.baidu.com/s/1dFr2m

引入命名空间:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;

这三个就好了。

代码一:

 /// <summary>
/// 创建工作簿
/// </summary>
/// <param name="fileName">下载文件名</param>
/// <param name="dt">数据源</param>
public static void CreateSheet(string fileName, DataTable dt)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream(); //创建一个名称为Payment的工作表
ISheet paymentSheet = workbook.CreateSheet("游戏得分用户表"); //数据源
DataTable tbPayment = dt; #region 头部标题
IRow paymentHeaderRow = paymentSheet.CreateRow(0); ICell cell = paymentHeaderRow.CreateCell(0);
cell.SetCellValue("游戏得分用户信息");
ICellStyle style = workbook.CreateCellStyle(); style.Alignment = HorizontalAlignment.CENTER;
IFont font = workbook.CreateFont();
font.FontHeight = 20 * 20;
font.Color = HSSFColor.RED.index;
style.SetFont(font); //合并单元格,以下是合并第一行五列
paymentSheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 4));
cell.CellStyle = style;
int rowsNum = 1;
paymentHeaderRow = paymentSheet.CreateRow(rowsNum); paymentHeaderRow.CreateCell(0, CellType.STRING).SetCellValue("用户名");
paymentHeaderRow.CreateCell(1, CellType.STRING).SetCellValue("手机号码");
paymentHeaderRow.CreateCell(2, CellType.NUMERIC).SetCellValue("得分");
paymentHeaderRow.CreateCell(3, CellType.STRING).SetCellValue("创建时间");
//paymentHeaderRow.CreateCell(4,CellType.STRING).SetCellValue("IP");
#endregion //循环添加标题
//foreach (DataColumn column in tbPayment.Columns)
// paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // 内容
int paymentRowIndex = 2;
foreach (DataRow row in tbPayment.Rows)
{
IRow newRow = paymentSheet.CreateRow(paymentRowIndex); //循环添加列的对应内容
foreach (DataColumn column in tbPayment.Columns)
{
newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} paymentRowIndex++;
} //列宽自适应,只对英文和数字有效
for (int i = 0; i <= dt.Rows.Count; i++)
{
paymentSheet.AutoSizeColumn(i);
}
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = 0; columnNum <= dt.Rows.Count; columnNum++)
{
int columnWidth = paymentSheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 1; rowNum <= paymentSheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (paymentSheet.GetRow(rowNum) == null)
{
currentRow = paymentSheet.CreateRow(rowNum);
}
else
{
currentRow = paymentSheet.GetRow(rowNum);
} if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
paymentSheet.SetColumnWidth(columnNum, columnWidth * 256);
} //将表内容写入流 通知浏览器下载
workbook.Write(ms);
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName));
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //进行二进制流下在 workbook = null;
ms.Close();
ms.Dispose();
}

  

代码二:

 /// <summary>
/// List集合转变成Datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public DataTable ConvertToDataSet<T>(IList<T> list)
{
if (list == null || list.Count <= 0)
{
return null;
} DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("UserPhone", typeof(string));
dt.Columns.Add("Score", typeof(int));
dt.Columns.Add("CreateDate", typeof(DateTime));
//dt.Columns.Add("CreateIP", typeof(string)); System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (T t in list)
{
if (t == null)
{
continue;
} row = dt.NewRow(); for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
} row[name] = pi.GetValue(t, null);
} dt.Rows.Add(row);
} return dt;
}

  

代码三:

  protected void btnExport_Click(object sender, EventArgs e)
{
var ss = ydc.GameScore.OrderByDescending(g => g.Score).GroupBy(g => g.UserPhone).Select(g => g.First()).ToList();
List<GameModel> gList = new List<GameModel>();
foreach (var item in ss)
{
GameModel gm = new GameModel();
gm.UserName = item.UserName;
gm.UserPhone = item.UserPhone;
gm.Score = item.Score;
gm.CreateDate = item.CreateDate;
//gm.CreateIP = item.CreateIP;
gList.Add(gm);
} //导出时避免没有数据而报错
if (gList.Count() > 0)
{
//导出成Excel
CreateSheet("gameScore", ConvertToDataSet(gList));
}
else
{
StringHelper.Alert(this, "没有数据不能进行导出操作!", "");
} }

  

NPOI使用Datatable导出到Excel的更多相关文章

  1. Npoi List DataTable导出一个Excel多个sheet 下载

    参考: http://blog.csdn.net/zhouqinghe24/article/details/8649346 参考下载http://www.cnblogs.com/dyllove98/a ...

  2. [转].net 使用NPOI或MyXls把DataTable导出到Excel

    本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...

  3. NPOI通过DataTable导出和读取Excel

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你得 ...

  4. DataTable导出到Excel

    简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...

  5. DataTable 导出到 Excel 类

    底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...

  6. c# DataTable导出为excel

    /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt& ...

  7. C# datatable 导出到Excel

    datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <pa ...

  8. csv/json/list/datatable导出为excel的通用模块设计

    导出excel的场景我一般都是一个List直接导出成一张sheet,用Npoi.Mapper库很方便,最近我经常是需要将接口返回的jsonarray转成一张excel表,比如从elasticsearc ...

  9. DataTable导出到Excel(.NET 4.0)

    最近在论坛里又看到很多关于DataTable(DataSet)导入Excel的帖子,我也温故知新一下,用VS2010重新整理了一个Sample.这个问题简化一下就是内存数据到文件,也就是遍历赋值,只不 ...

随机推荐

  1. Form类的KeyPreview属性

    首先需要知道一个知识点,Form控件,Panel控件和GroupBox控件等容器类控件默认是不接收焦点的,而是负责管理容器中控件的焦点.当容器控件被选中时,默认把焦点传送至容器内Tab顺序为0的控件. ...

  2. Ubuntu下载工具 uget+aria2

    一.安装. uget和aria2都可以在“软件中心”中安装,但是版本太老啦,无法发挥作用,所以最好还是在终端中添加ppa进行安装: 1.uget的安装:  sudo add-apt-repositor ...

  3. MFC实现为窗体添加的背景图片

    将一个bmp图片添加到资源中 在资源视图中更改位图资源的ID为IDB_BITMAP_BACKGROUND. 第一种方法: 在Dialog中添加一个Picture Control控件,将Picture ...

  4. 使用JavaCV/OpenCV抓取并存储摄像头图像

    http://blog.csdn.net/ljsspace/article/details/6702178  分类: 图形图像(3)  版权声明:本文为博主原创文章,未经博主允许不得转载. 本程序通过 ...

  5. PowerDesigner中逆向工程将数据库中comment赋值到name

    '------------------------------------------------------------ ' '脚本功能: ' PowerDesigner中逆向工程完成后,将数据库中 ...

  6. jq的事件对象的属性

    1.event.type() 该方法的作用是可以获取到时间的类型 $('a').click(function(){ alert(event.type);//获取事件类型 return  false;/ ...

  7. <a href="#" onclick="history.back();"></a>这样写为什么是对的? -(转)

    为什么不用这样写?<a href="#" onclick="javascript:history.back();"></a> 正解是: ...

  8. [其他]volatile 关键字

    用  volatile 关键字修饰函数 的作用是 告诉编译器该函数不会返回 , 让编译器能产生更好的代码 另外也能避免一些假警告信息,如未初始化的变量等

  9. AD进行行PCB DRC检查时,软件提示...report_drc.xsl不存在

    之前装过一次AD软件没有报过这样的错误,卸掉后重新装了之后,在对电气规则检查检查时“软件提示...report_drc.xsl不存在”. 原因:之前装的目录默认在C盘下,所以AD软件输出的报告也是默认 ...

  10. Jquery和Javascript对象之间的转换

    jQuery 对象是通过 jQuery 包装DOM 对象后产生的对象.jQuery 对象是 jQuery 独有的,其可以使用 jQuery 里的方法,但是不能使用 DOM 的方法:例如: $(&quo ...