NPOI使用Datatable导出到Excel
首先要引用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的更多相关文章
- Npoi List DataTable导出一个Excel多个sheet 下载
参考: http://blog.csdn.net/zhouqinghe24/article/details/8649346 参考下载http://www.cnblogs.com/dyllove98/a ...
- [转].net 使用NPOI或MyXls把DataTable导出到Excel
本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...
- NPOI通过DataTable导出和读取Excel
Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你得 ...
- DataTable导出到Excel
简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...
- DataTable 导出到 Excel 类
底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...
- c# DataTable导出为excel
/// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <param name="dt& ...
- C# datatable 导出到Excel
datatable导出到Excel /// <summary> /// 将DataTable导出为Excel文件(.xls) /// </summary> /// <pa ...
- csv/json/list/datatable导出为excel的通用模块设计
导出excel的场景我一般都是一个List直接导出成一张sheet,用Npoi.Mapper库很方便,最近我经常是需要将接口返回的jsonarray转成一张excel表,比如从elasticsearc ...
- DataTable导出到Excel(.NET 4.0)
最近在论坛里又看到很多关于DataTable(DataSet)导入Excel的帖子,我也温故知新一下,用VS2010重新整理了一个Sample.这个问题简化一下就是内存数据到文件,也就是遍历赋值,只不 ...
随机推荐
- php des 加密类
<?php/** *@see Yii CSecurityManager; */class Des{ public static function encrypt($data,$key){ $mo ...
- Android抽屉(SlidingDrawer --类似android通知栏下拉效果)
Android抽屉(SlidingDrawer)的实现发 - 红黑联盟http://www.2cto.com/kf/201301/182507.html 可动态布局的Android抽屉之基础http: ...
- 项目管理实践教程一、工欲善其事,必先利其器【Basic Tools】
今天,我们首先安装一些必须的软件,主要有下面的4个,其中软件1和2使用在服务器机上,软件3和4安装在客户端机上.另外,我们还有用到MSBuild.RoboCopy.WebDeployment等等,在下 ...
- jQuery checkbox 全选
jQuery 1.6版本以后 if($("#id").attr("checked")) 不能返回 ture 和 false 高版本中jQuery 提供prop ...
- Java 向Hbase表插入数据报(org.apache.hadoop.hbase.client.HTablePool$PooledHTable cannot be cast to org.apac
org.apache.hadoop.hbase.client.HTablePool$PooledHTable cannot be cast to org.apac 代码: //1.create HTa ...
- 前端知识复习一(css)
1.清楚浮动 父盒子高度为0,子盒子全部定位.浮动.子盒子不会撑开父盒子,下面的盒子会顶上来 清楚方法: clear:both: overflow:hidden: 加空标签 单/双 //双标签 .cl ...
- 双重检查锁定与延迟初始化(转自infoq)
很好的文章,转自http://www.infoq.com/cn/articles/double-checked-locking-with-delay-initialization 在java程序中,有 ...
- L3,please send me a card
expressions: a few words几句话 lend sb sth或lend sth to sb borrow sth或borrow sth from sb 都表示借,但是行为不同. wo ...
- 【转】bootstrap 的 affix.js 插件
我觉得 Twitter Bootstrap 提供的 JavaScript 插件可用性非常高,但文档多数简单.按部就班操作了,有效果当然好,没效果的话简直不知道为什么.之前我写过 Scrollspy 用 ...
- access restriction
一.既然存在访问规则,那么修改访问规则即可.打开项目的Build Path Configuration页面,打开报错的JAR包,选中Access rules条目,选择右侧的编辑按钮,添加一个访问规则即 ...