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工具类的更多相关文章

  1. C# NPOI 导出Execl 工具类

    NPOI 导出Execl 自己单独工具类 详见代码 using System; using System.Collections.Generic; using System.Linq; using S ...

  2. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  3. Android—关于自定义对话框的工具类

    开发中有很多地方会用到自定义对话框,为了避免不必要的城府代码,在此总结出一个工具类. 弹出对话框的地方很多,但是都大同小异,不同无非就是提示内容或者图片不同,下面这个类是将提示内容和图片放到了自定义函 ...

  4. [转]Java常用工具类集合

    转自:http://blog.csdn.net/justdb/article/details/8653166 数据库连接工具类——仅仅获得连接对象 ConnDB.java package com.ut ...

  5. js常用工具类.

    一些js的工具类 复制代码 /** * Created by sevennight on 15-1-31. * js常用工具类 */ /** * 方法作用:[格式化时间] * 使用方法 * 示例: * ...

  6. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  7. Java程序员的日常—— Arrays工具类的使用

    这个类在日常的开发中,还是非常常用的.今天就总结一下Arrays工具类的常用方法.最常用的就是asList,sort,toStream,equals,copyOf了.另外可以深入学习下Arrays的排 ...

  8. .net使用正则表达式校验、匹配字符工具类

    开发程序离不开数据的校验,这里整理了一些数据的校验.匹配的方法: /// <summary> /// 字符(串)验证.匹配工具类 /// </summary> public c ...

  9. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

随机推荐

  1. android 知识小结-1

    Java哪些数据结构是线程安全的,CurrentHashMap的原理 ConcurrentHashMap.ConcurrentSkipListMap.ConcurrentSkipListSet.Con ...

  2. CentOS下Docker的安装及国内镜像配置

    系统,CentOS 7,最小化安装. 升级包 >$ sudo yum upgrade 安装Docker >$ sudo yum install docker 下面开始配置国内镜像.国外的实 ...

  3. Web 端屏幕适配方案

    基础知识 像素相关 1.像素 :像素是屏幕显示最小的单位. 2.设备像素 :设备像素又称物理像素(physical pixel),设备能控制显示的最小单位,我们可以把这些像素看作成显示器上一个个的点. ...

  4. New Concept English Two 30 82

    $课文80  水晶宫 867. Perhaps the most extraordinary building of the nineteeth century was the Crystal Pal ...

  5. Editor does not contain a main type

    1.错误描述 2.错误原因 在含有main方法的类中,运行应用程序,却提示这个错误:编译器不包含main类型 3.解决办法 (1)选择该Java类上一级文件,build path--->use ...

  6. threejs通过射线Ray获取指定的点

    例:获取cube方向上的面的中点坐标(该cube默认方向为(0,1,0)) (中心点向cube quaternion 方向上发射射线,与正前方的面相交的点即为目标点; 由于ray只支持box和face ...

  7. rabbitmq学习(三):rabbitmq之扇形交换机、主题交换机

    前言 上篇我们学习了rabbitmq的作用以及直连交换机的代码实现,这篇我们继续看如何用代码实现扇形交换机和主题交换机 一.扇形交换机 1.生产者 /** * 生产者 */ public class ...

  8. 【项目经验】macpro上安装office办公软件并破解

    链接: https://pan.baidu.com/s/1i5hyKO9 密码: 7zjf 如果本机原有office,先卸载 双击pkg文件安装office for Mac 2016 安装完不要做打开 ...

  9. test20181019 B君的第二题

    题意 分析 快速子集和变换以及快速超集和变换的裸题. 用\(f(s)\)表示集合s的方案数,初始化为输入中s出现的次数. 做一遍快速子集和变换,此时f(s)表示s及其子集在输入中出现的次数. 对所有f ...

  10. OLEDB操作Excel

    使用OLEDB操作Excel 的方法 OleDbConnection conn = null;            try            {              //fileName ...