NPOI工具类
NPOI调用方法
DataTable dt = new DataTable();
Dictionary<string, string> header = new Dictionary<string, string>(); header.Add("UserName", "姓名");
header.Add("SignCity", "地区");
header.Add("UserPhone", "联系方式");//list转datatable var ExcleList =null; //查询list集合
dt = Dscf.Global.NpoiUtil.List2DataTable(ExcleList, header);
Dscf.Global.NpoiUtil.ExportExcel(dt);
内存表转文件流
#region 内存表转文件流
/// <summary>
/// 转换内存表为EXCEL文件流(行数超过65535,sheet分页)
/// </summary>
/// <param name="SourceTable">源数据</param>
/// <param name="sheetSize">sheet最大行数,不大于65535</param>
/// <param name="DateTimeFormat">时间列格式化</param>
/// <returns>EXCEL文件流</returns>
public static Stream RenderDataTableToPagingExcelStream(DataTable SourceTable, int sheetSize = 65535, string DateTimeFormat = "yyyy-MM-dd HH:mm:ss")
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
IDataFormat dataformat = workbook.CreateDataFormat();
ICellStyle style = workbook.CreateCellStyle();
int count = SourceTable.Rows.Count;
int total = count / sheetSize + (count % sheetSize > 0 ? 1 : 0);
for (
int sheetIndex = 0;
sheetIndex < total;
sheetIndex++)
{
ISheet sheet = workbook.CreateSheet();
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in SourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
// handling value.
int rowIndex = 1;
for (int i = sheetIndex * sheetSize;
i < (total.Equals(sheetIndex + 1) ? count : (sheetIndex + 1) * sheetSize);
i++)
{
DataRow row = SourceTable.Rows[i];
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in SourceTable.Columns)
{
if (row[column] is DBNull)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(string.Empty);
continue;
}
if (column.DataType == typeof(int))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((int)row[column]);
}
else if (column.DataType == typeof(float))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((float)row[column]);
}
else if (column.DataType == typeof(double))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((double)row[column]);
}
else if (column.DataType == typeof(Byte))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((byte)row[column]);
}
else if (column.DataType == typeof(UInt16))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt16)row[column]);
}
else if (column.DataType == typeof(UInt32))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt32)row[column]);
}
else if (column.DataType == typeof(UInt64))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt64)row[column]);
}
else if (column.DataType == typeof(DateTime))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((DateTime)row[column]);
style.DataFormat = dataformat.GetFormat(DateTimeFormat);
dataRow.GetCell(column.Ordinal).CellStyle = style;
}
else
{
dataRow.CreateCell(column.Ordinal).SetCellValue(Convert.ToString(row[column]));
}
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
}
workbook = null;
return ms;
}
/// <summary>
/// 转换内存表为EXCEL文件流
/// </summary>
/// <param name="SourceTable">源数据</param>
/// <param name="DateTimeFormat">时间列格式化</param>
/// <returns>EXCEL文件流</returns>
public static Stream RenderDataTableToExcelStream(DataTable SourceTable, string DateTimeFormat = "yyyy-MM-dd HH:mm:ss")
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ISheet sheet = workbook.CreateSheet();
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in SourceTable.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
// handling value.
int rowIndex = 1;
foreach (DataRow row in SourceTable.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
IDataFormat dataformat = workbook.CreateDataFormat();
ICellStyle style = workbook.CreateCellStyle();
foreach (DataColumn column in SourceTable.Columns)
{
if (row[column] is DBNull)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(string.Empty);
continue;
}
if (column.DataType == typeof(int))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((int)row[column]);
}
else if (column.DataType == typeof(float))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((float)row[column]);
}
else if (column.DataType == typeof(double))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((double)row[column]);
}
else if (column.DataType == typeof(Byte))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((byte)row[column]);
}
else if (column.DataType == typeof(UInt16))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt16)row[column]);
}
else if (column.DataType == typeof(UInt32))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt32)row[column]);
}
else if (column.DataType == typeof(UInt64))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((UInt64)row[column]);
}
else if (column.DataType == typeof(DateTime))
{
dataRow.CreateCell(column.Ordinal).SetCellValue((DateTime)row[column]);
style.DataFormat = dataformat.GetFormat(DateTimeFormat);
dataRow.GetCell(column.Ordinal).CellStyle = style;
}
else
{
dataRow.CreateCell(column.Ordinal).SetCellValue(Convert.ToString(row[column]));
}
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
workbook = null;
return ms;
}
#endregion
文件流转内存表
#region 文件流转内存表
/// <summary>
/// 将EXCEL文件流转换成内存表
/// </summary>
/// <param name="ExcelFileStream">EXCEL文件流</param>
/// <param name="SheetName">表名</param>
/// <param name="HeaderRowIndex">标题索引</param>
/// <returns></returns>
public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex)
{
HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);
ISheet sheet = workbook.GetSheet(SheetName);
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(HeaderRowIndex);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i < sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
dataRow[j] = row.GetCell(j).ToString();
}
ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
}
/// <summary>
/// 将EXCEL文件流转换成内存表
/// </summary>
/// <param name="ExcelFileStream"></param>
/// <param name="file"></param>
/// <param name="SheetIndex"></param>
/// <param name="HeaderRowIndex"></param>
/// <returns></returns>
public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string file, int SheetIndex, int HeaderRowIndex)
{
IWorkbook workbook = null;
string fileExt = Path.GetExtension(file);
if (fileExt == ".xls")
{
workbook = new HSSFWorkbook(ExcelFileStream);
}
else if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook(ExcelFileStream);
}
ISheet sheet = workbook.GetSheetAt(SheetIndex);
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(HeaderRowIndex);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = 0; i < rowCount + 1; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j <= cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
table.Rows.Add(dataRow);
}
table.Rows.RemoveAt(0);
ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
}
#endregion
文件下载与导出
#region 文件下载与导出
/// <summary>
/// 导出Excel文件
/// </summary>
/// <param name="dt">内存表</param>
/// <param name="fileName">文件名(不要包含后缀)</param>
/// <param name="sheetSize">sheet最大行数,不大于65535</param>
public static void ExportExcel(DataTable dt, string fileName = "", int sheetSize = 1023)
{
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}.xls",
string.IsNullOrWhiteSpace(fileName) ?
DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") :
fileName));
using (MemoryStream ms = (dt.Rows.Count > sheetSize ? RenderDataTableToPagingExcelStream(dt, sheetSize) : RenderDataTableToPagingExcelStream(dt)) as MemoryStream)
{
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
/// <summary>
/// 导出Excel文件请求
/// </summary>
/// <param name="dt">内存表</param>
/// <param name="fileName">文件名(不要包含后缀)</param>
/// <param name="sheetSize">sheet最大行数,不大于65535</param>
public static HttpResponseMessage ExportExcelResponse(DataTable dt, string fileName = "", int sheetSize = 1023)
{
//创建HTTP请求内容
HttpResponseMessage httpRspMsg = new HttpResponseMessage(HttpStatusCode.OK);
httpRspMsg.Content = new StreamContent(
dt.Rows.Count > sheetSize ?
RenderDataTableToPagingExcelStream(dt, sheetSize) :
RenderDataTableToExcelStream(dt));
//通知浏览器下载文件而不是打开
httpRspMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpRspMsg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = string.Format("{0}.xls",
string.IsNullOrWhiteSpace(fileName) ?
DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") :
fileName)
};
return httpRspMsg;
}
/// <summary>
/// 下载本地目录的EXCEL文件
/// </summary>
/// <param name="filePath">完整文件目录</param>
/// <param name="fileName">重命名下载文件名称(不要包含后缀名)</param>
public static void DownLoadFile(string filePath, string fileName = "")
{
//文件后缀
string fileExt = Path.GetExtension(filePath);
if (fileExt.ToLower().IndexOf("xls") < 0)
throw new Exception("不能下载非EXCEL格式的文件!");
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}",
string.IsNullOrWhiteSpace(fileName) ?
Path.GetFileName(filePath) :
fileName + fileExt));
//以字符流的形式下载文件
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
HttpContext.Current.Response.BinaryWrite(bytes);
bytes = null;
}
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
/// <summary>
/// 将内存表转换的EXCEL文件保存到本地
/// </summary>
/// <param name="SourceTable">源数据</param>
/// <param name="FileName">文件名</param>
public static void RenderDataTableToExcel(DataTable SourceTable, string FileName)
{
using (MemoryStream ms = RenderDataTableToExcelStream(SourceTable) as MemoryStream)
{
using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
data = null;
}
}
}
#endregion
List转DataTable
#region List转DataTable
/// <summary>
/// List转DataTable
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="list">列表</param>
/// <param name="header">列头</param>
/// <returns></returns>
public static DataTable List2DataTable<T>(List<T> list, IDictionary<string, string> header = null) where T : class
{
//如果header无效
if (header == null || header.Count == 0)
return GetDataTable(list, typeof(T));
DataTable dt = new DataTable();
PropertyInfo[] p = typeof(T).GetProperties();
foreach (PropertyInfo pi in p)
{
//源数据实体是否包含header列
if (header.ContainsKey(pi.Name))
{
// The the type of the property
Type columnType = pi.PropertyType;
// We need to check whether the property is NULLABLE
if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
columnType = pi.PropertyType.GetGenericArguments()[0];
}
dt.Columns.Add(header[pi.Name], columnType);
}
}
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
IList tempList = new ArrayList();
foreach (PropertyInfo pi in p)
{
object o = pi.GetValue(list[i], null);
if (header == null || header.Count == 0 || //如果header无效
header.ContainsKey(pi.Name)) // 或源数据实体包含header列
{
tempList.Add(o);
}
}
object[] itm = new object[header.Count];
for (int j = 0; j < tempList.Count; j++)
{
itm.SetValue(tempList[j], j);
}
dt.LoadDataRow(itm, true);
}
}
return dt;
}
/// <summary>
/// Converts a Generic List into a DataTable
/// </summary>
/// <param name="list"></param>
/// <param name="typ"></param>
/// <returns></returns>
public static DataTable GetDataTable(IList list, Type typ)
{
DataTable dt = new DataTable();
// Get a list of all the properties on the object
PropertyInfo[] pi = typ.GetProperties();
// Loop through each property, and add it as a column to the datatable
foreach (PropertyInfo p in pi)
{
// The the type of the property
Type columnType = p.PropertyType;
// We need to check whether the property is NULLABLE
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
columnType = p.PropertyType.GetGenericArguments()[0];
}
// Add the column definition to the datatable.
dt.Columns.Add(new DataColumn(p.Name, columnType));
}
// For each object in the list, loop through and add the data to the datatable.
foreach (object obj in list)
{
object[] row = new object[pi.Length];
int i = 0;
foreach (PropertyInfo p in pi)
{
row[i++] = p.GetValue(obj, null);
}
dt.Rows.Add(row);
}
return dt;
}
#endregion
NPOI工具类的更多相关文章
- C# NPOI 导出Execl 工具类
NPOI 导出Execl 自己单独工具类 详见代码 using System; using System.Collections.Generic; using System.Linq; using S ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Android—关于自定义对话框的工具类
开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...
- [转]Java常用工具类集合
转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...
- js常用工具类.
一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...
- Guava库介绍之实用工具类
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...
- Java程序员的日常—— Arrays工具类的使用
这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...
- .net使用正则表达式校验、匹配字符工具类
开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
随机推荐
- SharePoint Development - Custom List using Visual Studio 2010 based SharePoint 2010
博客地址 http://blog.csdn.net/foxdave 之前两次我们定义了内容类型和字段,我们现在用它们为这一讲服务--创建一个自定义列表. 打开Visual Studio,打开之前的工程 ...
- 选择语句=》OO函数实现
let a; let b; if (a==="A") { b='定向' }else if (a==='B') { b='开放' }else if(a==='C') { b='全部' ...
- PyalgoTrade 技术组合计算(四)
可以各种技术可以组合起来.它们被建模为DataSeries.例如,在收盘价之上获得RSI以上的计算SMA,是非常简单的: from pyalgotrade import strategy from p ...
- BZOJ3195: [Jxoi2012]奇怪的道路【状压DP】
Description 小宇从历史书上了解到一个古老的文明.这个文明在各个方面高度发达,交通方面也不例外.考古学家已经知道,这个文明在全盛时期有n座城市,编号为1..n.m条道路连接在这些城市之间,每 ...
- 6-11 Level-order Traversal(25 分)
Write a routine to list out the nodes of a binary tree in "level-order". List the root, th ...
- Ext.js基础
第一章:Ext.js基础 好书推荐 Javascript设计模式 征服ajax web 2.0开发技术详解 简介 基础要求 了解HTML.CSS.熟练JS.JS的OOP.AJAX JSP/PHP/AS ...
- 【小白的java成长系列】——windows下搭建和配置java环境
版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/enson16855/article/details/25967851 基于非常多原因,还是得说说ja ...
- Android - 传统蓝牙通信聊天
Android -传统蓝牙通信聊天 技术:java+Android4.4+jdk1.8 运行环境:Android4.4.Android7.0 概述 Android 传统蓝牙的使用,包括开关蓝牙.搜索设 ...
- Windows 2008 关闭远程桌面的单用户多会话模式
Windows 2008 关闭远程桌面的单用户多会话模式 在腾讯云上购买了一台云服务器. 因为设置了自动登录,在远程桌面连接后会启动一个新的会话,然后软件被运行了两次,端口被占用,无法起动. 还有可能 ...
- 【python】使用HTMLParser、cookielib抓取和解析网页、从HTML文档中提取链接、图像、文本、Cookies
一.从HTML文档中提取链接 模块HTMLParser,该模块使我们能够根据HTML文档中的标签来简洁.高效地解析HTML文档. 处理HTML文档的时候,我们常常需要从其中提取出所有的链接.使用HTM ...