NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下:

首先说明几点:

1.Excel2003及一下:后缀xls,单个sheet最大行数为65335

Excel2007 单个sheet :后缀xlsx 单个sheet 最大行数为 1048576

2.在用NPOI.dll时,导出的excel两种形式(xls,xlsx)用到的组件不一样,xls是HSSF,xlsx是XSSF,

由于某种原因我选择的是HSSF组件的:
以linq 匿名类得到数据为数据源导出Excel
类如以这样为数据源的:

var buildingCustomsPass = from CityBuilding in cityBuilding
select new
{

MapBuildingModelID = 0,
MapModelID = 0,
BuildingModelID = CityBuilding.BuildingModelID,
BuildingLevel = CityBuilding.BuildingLevel,
UnitPosX = CityBuilding.UnitPosX,
UnitPosY = CityBuilding.UnitPosY,
GarrisonIndex = 0,
BuildingUID = CityBuilding.BuildingUID
};

做的时候利用的是NPOI.dll这个开源项目,当然要引入NPOI.dll(自己网上搜,很多,这里就不提供了)

一:Excel导出单个sheet

//创建一个有Excel(构造的大概框架,标题)
public HSSFWorkbook CreateExcel(string[] titles)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();

//标题样式
ICellStyle cellStyleLable = sheet.Workbook.CreateCellStyle();
cellStyleLable.Alignment = HorizontalAlignment.CENTER;
cellStyleLable.VerticalAlignment = VerticalAlignment.CENTER;
cellStyleLable.FillPattern = FillPatternType.SOLID_FOREGROUND;
cellStyleLable.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
//设置字体
IFont font = workbook.CreateFont();
font.Boldweight = (short)FontBoldWeight.BOLD;
cellStyleLable.SetFont(font);

//文本样式
 //ICellStyle cellStyleText = sheet.Workbook.CreateCellStyle();
 //cellStyleText.Alignment = HorizontalAlignment.CENTER;
 //cellStyleText.VerticalAlignment = VerticalAlignment.CENTER;
 //cellStyleText.BorderBottom = BorderStyle.THIN;
 //cellStyleText.BorderTop = BorderStyle.THIN;
 //cellStyleText.BorderRight = BorderStyle.THIN;
 //cellStyleText.BorderLeft = BorderStyle.THIN;

IRow row = sheet.CreateRow(0);
 for (int i = 0; i < titles.Length; i++)
{
ICell cell = row.CreateCell(i);
cell.CellStyle = cellStyleLable;
cell.SetCellValue(titles[i]);

sheet.SetColumnWidth(i, 20 * 256);

}
 return workbook;
}

//导出

protected void ButtonExport_Click(object sender, EventArgs e){

这里是以linq得到的匿名类为数据源

var buildingCustomsPass = from CityBuilding in cityBuilding
select new
{

MapBuildingModelID = 0,
MapModelID = 0,
BuildingModelID = CityBuilding.BuildingModelID,
BuildingLevel = CityBuilding.BuildingLevel,
UnitPosX = CityBuilding.UnitPosX,
UnitPosY = CityBuilding.UnitPosY,
GarrisonIndex = 0,
BuildingUID = CityBuilding.BuildingUID
};
if (buildingCustomsPass.Count() > 0)
{
HSSFWorkbook workbook = CreateExcel(new string[] { "MapBuildingModelID", "MapModelID", "BuildingModelID", "BuildingLevel", "UnitPosX", "UnitPosY", "GarrisonIndex" });

int i = 0;

foreach (var building in buildingCustomsPass)
{
 IRow row = workbook.GetSheetAt(0).CreateRow(i + 1);
 row.CreateCell(0).SetCellValue(building.MapBuildingModelID);
 row.CreateCell(1).SetCellValue(building.MapModelID);
row.CreateCell(2).SetCellValue(building.BuildingModelID);
row.CreateCell(3).SetCellValue(building.BuildingLevel);
row.CreateCell(4).SetCellValue(building.UnitPosX);
row.CreateCell(5).SetCellValue(building.UnitPosY);
row.CreateCell(6).SetCellValue(building.GarrisonIndex);
 i = i + 1;

}

MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();

}

二.Excel 多个sheet(这里是数据超过65335时写入另一个sheet)

/// <summary>
/// 生成Excel表头(这里只是生成表头)
/// </summary>
/// <param name="sheet"></param>
/// <param name="titles"></param>
public void CreateHeader(HSSFSheet sheet, string[] titles)
{
//标题样式
ICellStyle cellStyleLable = sheet.Workbook.CreateCellStyle();
cellStyleLable.Alignment = HorizontalAlignment.CENTER;
cellStyleLable.VerticalAlignment = VerticalAlignment.CENTER;
cellStyleLable.FillPattern = FillPatternType.SOLID_FOREGROUND;
cellStyleLable.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
IRow row = sheet.CreateRow(0);
for (int i = 0; i < titles.Length; i++)
{
ICell cell = row.CreateCell(i);
cell.CellStyle = cellStyleLable;
cell.SetCellValue(titles[i]);
sheet.SetColumnWidth(i, 20 * 256);
}
}

//导出

protected void ButtonExporet_Click(object sender, EventArgs e){

NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();

var customFighter = from
CityFighter in cityFighter
select new { CustomFighterSetID =0,
CustomModelID = 0,
FighterModelID = CityFighter.FighterModelID,
FighterLevel = CityFighter.FighterLevel,
IsForeignAid = 0,
BonusRatePer =0 };
if (customFighter.Count() > 0)
{
int rowCount = 0;
int sheetCount = 1;
//添加一个sheet
NPOI.SS.UserModel.ISheet newSheet = null;
newSheet = book.CreateSheet("Sheet" + sheetCount);

CreateHeader((HSSFSheet)newSheet, new string[] { "CustomFighterSetID", "CustomModelID", "FighterModelID", "FighterLevel", "IsForeignAid", "BonusRatePer" });
foreach (var fighter in customFighter)
{
rowCount++;
if (rowCount == 65335)
{
rowCount = 1;
sheetCount++;
newSheet = book.CreateSheet("Sheet" + sheetCount);
CreateHeader((HSSFSheet)newSheet, new string[] { "CustomFighterSetID", "CustomModelID", "FighterModelID", "FighterLevel", "IsForeignAid", "BonusRatePer" });
}
// IRow row = book.GetSheetAt(sheetCount).CreateRow(rowCount + 1);
IRow row = newSheet.CreateRow(rowCount);
row.CreateCell(0).SetCellValue(fighter.CustomFighterSetID);
row.CreateCell(1).SetCellValue(fighter.CustomModelID);
row.CreateCell(2).SetCellValue(fighter.FighterModelID);
row.CreateCell(3).SetCellValue(fighter.FighterLevel);
row.CreateCell(4).SetCellValue(fighter.IsForeignAid);
row.CreateCell(5).SetCellValue(fighter.BonusRatePer);
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();

}

三.Excel下的重新的sheet(类似2)

/// <summary>
/// 生成Excel头
/// </summary>
/// <param name="sheet"></param>
/// <param name="titles"></param>
public void CreateHeader(HSSFSheet sheet, string[] titles)
{
//标题样式
ICellStyle cellStyleLable = sheet.Workbook.CreateCellStyle();
cellStyleLable.Alignment = HorizontalAlignment.CENTER;
cellStyleLable.VerticalAlignment = VerticalAlignment.CENTER;
cellStyleLable.FillPattern = FillPatternType.SOLID_FOREGROUND;
cellStyleLable.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
cellStyleLable.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.WHITE.index;
IRow row = sheet.CreateRow(0);
for (int i = 0; i < titles.Length; i++)
{
ICell cell = row.CreateCell(i);
cell.CellStyle = cellStyleLable;
cell.SetCellValue(titles[i]);
sheet.SetColumnWidth(i, 20 * 256);
}
}

//开始导出 这里是导出一个Excel里面有来自三个数据源生成三个sheet

protected void ButtonSearch_export(object sender, EventArgs e)

{

if (playerInfo != null)
{
DBContext dbContext = DBHelper.GetGameDBContext(iServerId);
using (ISession session = dbContext.OpenSession())
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//sheet
NPOI.SS.UserModel.ISheet newSheet = null;
PlayerCity[] playerCity = session.CreateCriteria(typeof(PlayerCity)).Add(Restrictions.Eq("PlayerUID", playerInfo.PlayerUID)).List<PlayerCity>().ToArray();
ICollection<CityBuilding> cityBuilding = session.CreateCriteria(typeof(CityBuilding)).Add(Restrictions.Eq("CityUID", playerCity[0].CityUID)).List<CityBuilding>().ToArray();
var buildingCustomsPass = from CityBuilding in cityBuilding
select new
{
MapBuildingModelID = 0,
MapModelID = 0,
BuildingModelID = CityBuilding.BuildingModelID,
BuildingLevel = CityBuilding.BuildingLevel,
UnitPosX = CityBuilding.UnitPosX,
UnitPosY = CityBuilding.UnitPosY,
GarrisonIndex = 0,
BuildingUID = CityBuilding.BuildingUID
};
if (buildingCustomsPass.Count() > 0)
{
int rowCount = 0;
newSheet = book.CreateSheet("建筑");
CreateHeader((HSSFSheet)newSheet, new string[] { "MapBuildingModelID", "MapModelID", "BuildingModelID", "BuildingLevel", "UnitPosX", "UnitPosY", "GarrisonIndex", "BuildingUID" });
foreach (var building in buildingCustomsPass)
{
rowCount++;
IRow row = newSheet.CreateRow(rowCount);
row.CreateCell(0).SetCellValue(building.MapBuildingModelID);
row.CreateCell(1).SetCellValue(building.MapModelID);
row.CreateCell(2).SetCellValue(building.BuildingModelID);
row.CreateCell(3).SetCellValue(building.BuildingLevel);
row.CreateCell(4).SetCellValue(building.UnitPosX);
row.CreateCell(5).SetCellValue(building.UnitPosY);
row.CreateCell(6).SetCellValue(building.GarrisonIndex);
row.CreateCell(7).SetCellValue(building.BuildingUID.ToString());

}
newSheet = null;
}
//英雄
Guid guid = new Guid("00000000-0000-0000-0000-000000000000");
ICollection<CityWarrior> cityWarrior = session.CreateCriteria(typeof(CityWarrior)).Add(Restrictions.Eq("CityUID", playerCity[0].CityUID)).Add(Restrictions.Not(Restrictions.Eq("BuildingUID", guid))).List<CityWarrior>().ToArray();
var customWarrior = from CityWarrior in cityWarrior
select new
{
CustomWarriorSetID = 0,
CustomModelID = 0,
WarriorModelID = CityWarrior.WarriorModelID,
Rank = CityWarrior.Rank,
FighterLevel = CityWarrior.FighterLevel,
Coordination = CityWarrior.Coordination,
Formation_STR = CityWarrior.Formation_STR,
SpellsLevelSet_STR = CityWarrior.SpellsLevelSet_STR,
EquimentSpellsSlot = CityWarrior.EquimentSpellsSlot,
AstrolabeSlotState_STR = CityWarrior.AstrolabeSlotState_STR,
DetachTime = 0,
UnitPosX = 0,
UnitPosY = 0,
Direction = 0,
GarrisonIndex = 0,
IsForeignAid = 0,
HitRate = 0,
BonusRatePer = 0,
HitPointBonusRatePer = 0,
DamageBonusRatePer = 0,
DefenseBonusRatePer = 0
};
if (customWarrior.Count() > 0)
{
int rowCount = 0;
newSheet = book.CreateSheet("英雄");
CreateHeader((HSSFSheet)newSheet, new string[] { "CustomWarriorSetID", " CustomModelID", "WarriorModelID", "Rank", "FighterLevel", "Coordination", "Formation_STR", "SpellsLevelSet_STR", "EquimentSpellsSlot ", "AstrolabeSlotState_STR", "DetachTime", "UnitPosX", "UnitPosY", "Direction", "GarrisonIndex", "IsForeignAid", "HitRate", "BonusRatePer", "HitPointBonusRatePer", "DamageBonusRatePer", "DefenseBonusRatePer" });
foreach (var warrior in customWarrior)
{
rowCount++;
IRow row = newSheet.CreateRow(rowCount);
row.CreateCell(0).SetCellValue(warrior.CustomWarriorSetID);
row.CreateCell(1).SetCellValue(warrior.CustomModelID);
row.CreateCell(2).SetCellValue(warrior.WarriorModelID);
row.CreateCell(3).SetCellValue(warrior.Rank.ToString());
row.CreateCell(4).SetCellValue(warrior.FighterLevel);
row.CreateCell(5).SetCellValue(warrior.Coordination.ToString());
row.CreateCell(6).SetCellValue(warrior.Formation_STR);
row.CreateCell(7).SetCellValue(warrior.SpellsLevelSet_STR);
row.CreateCell(8).SetCellValue(warrior.EquimentSpellsSlot);
row.CreateCell(9).SetCellValue(warrior.AstrolabeSlotState_STR);
row.CreateCell(10).SetCellValue(warrior.DetachTime);
row.CreateCell(11).SetCellValue(warrior.UnitPosX);
row.CreateCell(12).SetCellValue(warrior.UnitPosY);
row.CreateCell(13).SetCellValue(warrior.Direction.ToString());
row.CreateCell(14).SetCellValue(warrior.GarrisonIndex);
row.CreateCell(15).SetCellValue(warrior.IsForeignAid);
row.CreateCell(16).SetCellValue(warrior.HitRate);
row.CreateCell(17).SetCellValue(warrior.BonusRatePer);
row.CreateCell(18).SetCellValue(warrior.HitPointBonusRatePer);
row.CreateCell(19).SetCellValue(warrior.DamageBonusRatePer);
row.CreateCell(20).SetCellValue(warrior.DefenseBonusRatePer);
}
newSheet = null;
}
ICollection<CityFighter> cityFighter = session.CreateCriteria(typeof(CityFighter)).Add(Restrictions.Eq("CityUID", playerCity[0].CityUID)).List<CityFighter>().ToArray();
var customFighter = from
CityFighter in cityFighter
select new
{
CustomFighterSetID = 0,
CustomModelID = 0,
FighterModelID = CityFighter.FighterModelID,
FighterLevel = CityFighter.FighterLevel,
IsForeignAid = 0,
BonusRatePer = 0
};
if (customFighter.Count() > 0)
{
int rowCount = 0;
newSheet = book.CreateSheet("部队");
CreateHeader((HSSFSheet)newSheet, new string[] { "CustomFighterSetID", "CustomModelID", "FighterModelID", "FighterLevel", "IsForeignAid", "BonusRatePer" });
foreach (var fighter in customFighter)
{
rowCount++;
IRow row = newSheet.CreateRow(rowCount);
row.CreateCell(0).SetCellValue(fighter.CustomFighterSetID);
row.CreateCell(1).SetCellValue(fighter.CustomModelID);
row.CreateCell(2).SetCellValue(fighter.FighterModelID);
row.CreateCell(3).SetCellValue(fighter.FighterLevel);
row.CreateCell(4).SetCellValue(fighter.IsForeignAid);
row.CreateCell(5).SetCellValue(fighter.BonusRatePer);
}
newSheet = null;
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
Response.BinaryWrite(ms.ToArray());
book = null;
ms.Close();
ms.Dispose();
}
}
else
{
LabelError.Text = "该玩家不存在";
return;
}

}

用到了就整理了一下,table数据源导出,类似上面,只是循环出table中的数据

NPOI导出Excel(含有超过65335的处理情况)的更多相关文章

  1. NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters

    /******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...

  2. .NET NPOI导出Excel详解

    NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...

  3. Asp.Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  4. NPOI导出EXCEL 打印设置分页及打印标题

    在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置  sheet1.FitToPage = false; 而 ...

  5. [转]NPOI导出EXCEL 打印设置分页及打印标题

    本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...

  6. 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限

    大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...

  7. 用NPOI导出Excel

    用NPOI导出Excel public void ProcessRequest(HttpContext context) { context.Response.ContentType = " ...

  8. NPOI导出Excel示例

    摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...

  9. NPOI导出excel(带图片)

    近期项目中用到Excel导出功能,之前都是用普通的office组件导出的方法,今天尝试用下NPOI,故作此文以备日后查阅. 1.NPOI官网http://npoi.codeplex.com/,下载最新 ...

随机推荐

  1. Nginx的nginx.conf配置文件中文注释说明

    #运行用户    user www-data;        #启动进程,通常设置成和cpu的数量相等    worker_processes  1;    #全局错误日志及PID文件    erro ...

  2. java规范(二)

    常量命名 不允许使用任何魔法值(未定义的常量)直接出现在代码中 反例: String key="Id#taobao_"+tradeId: cache.put(key, value) ...

  3. python之路-Day11

    引子 到目前为止,我们已经学了网络并发编程的2个套路, 多进程,多线程,这哥俩的优势和劣势都非常的明显,我们一起来回顾下 协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程: ...

  4. MySql的连接查询

    类似于oracle的连接查询,mysql连接查询也有左外连接.右外连接.内连接查询.但是,不同的是没有直接 的全外连接查询. 这里介绍MySql的连接查询: 这里已两张表为例:STUDENT 表 和 ...

  5. 转载:jQuery实现返回顶部功能

    转自:http://blog.csdn.net/itmyhome1990/article/details/25340705 整理两个实现功能,一个是右下角的返回顶部,一个是右侧的返回顶部,分别如图   ...

  6. Device nodes and device stacks

    [Device nodes and device stacks] 链接:https://msdn.microsoft.com/en-us/library/windows/hardware/ff5547 ...

  7. 初学c# -- 学习笔记(三)

    结合前面学的许多东西,写了一个小程序.会话.自定义滚动条.css等等.小程序没有用数据库,主要不知道该用哪种,以后再说吧.登录也简单,就输入用户名就可以了. 百度是个好东西,写程序时候,需要什么图就直 ...

  8. 关于CMFCPropertyGridFontProperty的赋值问题

    CMFCPropertyGridFontProperty是派生于CMFCPropertyGridProperty类的用于字体设置的类.它可以设置字体的名称.大小.粗细等各项参数.但是类并不提供用于初始 ...

  9. 解决:eclipse 非正常关闭,导致无法正常启动

    eclipse 无法正常启动: !ENTRY org.eclipse.ui.navigator 4 2 2016-09-07 11:23:54.181 !MESSAGE 从插件调用代码时出现问题:“o ...

  10. lua和整合实践

    这几天研究了一下lua,主要关注的是lua和vc之间的整合,把代码都写好放在VC宿主程序里,然后在lua里调用宿主程序的这些代码(或者叫接口.组件,随便你怎么叫),希望能用脚本来控制主程序的行为.这实 ...