NPOI导出Excel表功能实现(多个工作簿)(备用)
Excel生成操作类:
代码
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using System.Data; namespace StarTech.NPOI
{
/// <summary>
/// Excel生成操作类
/// </summary>
public class NPOIHelper
{
/// <summary>
/// 导出列名
/// </summary>
public static System.Collections.SortedList ListColumnsName;
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public static void ExportExcel(DataTable dtSource, string filePath)
{
if (ListColumnsName == null || ListColumnsName.Count == )
throw (new Exception("请对ListColumnsName设置要导出的列明!")); HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(dtSource, excelWorkbook);
SaveExcelFile(excelWorkbook, filePath);
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public static void ExportExcel(DataTable dtSource, Stream excelStream)
{
if (ListColumnsName == null || ListColumnsName.Count == )
throw (new Exception("请对ListColumnsName设置要导出的列明!")); HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(dtSource, excelWorkbook);
SaveExcelFile(excelWorkbook, excelStream);
}
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="excelWorkBook"></param>
/// <param name="filePath"></param>
protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, string filePath)
{
FileStream file = null;
try
{
file = new FileStream(filePath, FileMode.Create);
excelWorkBook.Write(file);
}
finally
{
if (file != null)
{
file.Close();
}
}
}
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="excelWorkBook"></param>
/// <param name="filePath"></param>
protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, Stream excelStream)
{
try
{
excelWorkBook.Write(excelStream);
}
finally
{ }
}
/// <summary>
/// 创建Excel文件
/// </summary>
/// <param name="filePath"></param>
protected static HSSFWorkbook CreateExcelFile()
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
return hssfworkbook;
}
/// <summary>
/// 创建excel表头
/// </summary>
/// <param name="dgv"></param>
/// <param name="excelSheet"></param>
protected static void CreateHeader(HSSFSheet excelSheet)
{
int cellIndex = ;
//循环导出列
foreach (System.Collections.DictionaryEntry de in ListColumnsName)
{
HSSFRow newRow = excelSheet.CreateRow();
HSSFCell newCell = newRow.CreateCell(cellIndex);
newCell.SetCellValue(de.Value.ToString());
cellIndex++;
}
}
/// <summary>
/// 插入数据行
/// </summary>
protected static void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
{
int rowCount = ;
int sheetCount = ;
HSSFSheet newsheet = null; //循环数据源导出数据集
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
foreach (DataRow dr in dtSource.Rows)
{
rowCount++;
//超出10000条数据 创建新的工作簿
if (rowCount == )
{
rowCount = ;
sheetCount++;
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
} HSSFRow newRow = newsheet.CreateRow(rowCount);
InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook);
}
}
/// <summary>
/// 导出数据行
/// </summary>
/// <param name="dtSource"></param>
/// <param name="drSource"></param>
/// <param name="currentExcelRow"></param>
/// <param name="excelSheet"></param>
/// <param name="excelWorkBook"></param>
protected static void InsertCell(DataTable dtSource, DataRow drSource, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
{
for (int cellIndex = ; cellIndex < ListColumnsName.Count; cellIndex++)
{
//列名称
string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
HSSFCell newCell = null;
System.Type rowType = drSource[columnsName].GetType();
string drValue = drSource[columnsName].ToString().Trim();
switch (rowType.ToString())
{
case "System.String"://字符串类型
drValue = drValue.Replace("&", "&");
drValue = drValue.Replace(">", ">");
drValue = drValue.Replace("<", "<");
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(dateV); //格式化显示
HSSFCellStyle cellStyle = excelWorkBook.CreateCellStyle();
HSSFDataFormat format = excelWorkBook.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
newCell.CellStyle = cellStyle; break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(intV.ToString());
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue("");
break;
default:
throw (new Exception(rowType.ToString() + ":类型数据无法处理!"));
}
}
}
}
//排序实现接口 不进行排序 根据添加顺序导出
public class NoSort : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return -;
}
}
}
Excel生成类
调用方法:
代码
//导出数据列 实现根据添加顺序导出列
StarTech.NPOI.NPOIHelper.ListColumnsName = new SortedList(new StarTech.NPOI.NoSort());
StarTech.NPOI.NPOIHelper.ListColumnsName.Add("MemberName", "姓名");
StarTech.NPOI.NPOIHelper.ListColumnsName.Add("username", "账号");
StarTech.NPOI.NPOIHelper.ListColumnsName.Add("starttime", "登陆时间");
StarTech.NPOI.NPOIHelper.ListColumnsName.Add("lasttime", "在线到期时间");
StarTech.NPOI.NPOIHelper.ListColumnsName.Add("state", "状态");
Response.Clear();
Response.BufferOutput = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
string filename = HttpUtility.UrlEncode(DateTime.Now.ToString("在线用户yyyyMMdd"));
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.ContentType = "application/ms-excel";
StarTech.NPOI.NPOIHelper.ExportExcel(dtSource, Response.OutputStream);
Response.Close();
调用Helper
NPOI导出Excel表功能实现(多个工作簿)(备用)的更多相关文章
- NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters
/******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...
- Asp.Net 使用Npoi导出Excel
引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...
- NPOI导出EXCEL 打印设置分页及打印标题
在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置 sheet1.FitToPage = false; 而 ...
- .NET NPOI导出Excel详解
NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...
- NPOI导出Excel(含有超过65335的处理情况)
NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...
- [转]NPOI导出EXCEL 打印设置分页及打印标题
本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...
- 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限
大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...
- 用NPOI导出Excel
用NPOI导出Excel public void ProcessRequest(HttpContext context) { context.Response.ContentType = " ...
- NPOI导出Excel示例
摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...
随机推荐
- Post 的数据被截断
原因: Form 域 POST 提交数据 100K(可能不是这个值) 限制的解决方案 因为微软这个限制是对表单内每个域(第一个控件)的限制.问题的解决办法是,对于一个需要发送大数据的域,在提交表单 ...
- 利用传入的Type类型来调用范型方法的解决方案
起因:自定义一个GridView控件,其数据源来源于一个通用方法Get<T>(),根据你传入的T到数据库中得到相应的数据,问题是定义GridView控件时没法在界面端设置使用泛型,只能在每 ...
- Codeforces Round #266 (Div. 2) D
D. Increase Sequence time limit per test 1 second memory limit per test 256 megabytes input standard ...
- ibatis的iterate使用
Iterate:这属性遍历整个集合,并为 List 集合中的元素重复元素体的内容. Iterate 的属性: prepend - 可被覆盖的 SQL 语句组成部分,添加在语句的前面(可选 ...
- leetcode course shedule
题目就不说了,问题本质就是在一个有向图中查找它是不是存在环. 上网百度了一下,方法是,找出图中入度为0 的点,将以它为起点的边去掉. 重复这一动作,直到所有的边都被去掉(没有环)或者存在边但是无法再去 ...
- POJ 3678
Katu Puzzle Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 7391 Accepted: 2717 Descr ...
- VMware 进入bios
在虚拟机创建目录中找到.vmx结尾的文件. 添加bios.forceSetupOnce = "TRUE". 打开虚拟机,他会自动进入bios,随后他会把bios.forceSetu ...
- .htaccess文件的作用(访问控制)
在线工具: http://www.htaccesseditor.com/sc.shtml 说到.htaccess文件,我想对于wordpress新手或者老手都应该不是很熟悉,也没有多少这方面的概念吧, ...
- 传说中的WCF(11):会话(Session)
在标题中我加了一个大家都很熟悉的单词——Session,熟吧?玩过Web开发的朋友肯定在梦中都会见到她. 在Web中为什么要会话呢?毕竟每个用户在一个Web应用中可能不止进行一次操作,比如,某二手飞机 ...
- 可灵活扩展的自定义Session状态存储驱动
Session是互联网应用中非常重要的玩意儿,对于超过单台部署的站点集群,都会存在会话共享的需求.在web.config中,微软提供了sessionstate节点来定义不同的Session状态存储方式 ...