一个简单的Excel帮助类,只支持数据集和数据表的导入导出。
帮助类,放到公共帮助类中
CommonEnum 枚举
namespace LchCommon
{
#region ExcelType Excel类型
/// <summary>
/// Excel类型
/// </summary>
public enum ExcelType
{
#region xls 2003
/// <summary>
/// xls 2003
/// </summary>
XLS = 1 << 0,
#endregion
#region xlsx 2007
/// <summary>
/// xls 2003
/// </summary>
XLSX = 1 << 1,
#endregion
}
#endregion
}
ExcelHelper帮助类
using System.Data;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace LchCommon.Helper
{
public class ExcelHelper
{
//=================== construct function ==================
#region construct construct
/// <summary>
/// construct
/// </summary>
public ExcelHelper()
{
}
#endregion
//=================== public metod ========================
/* 导出 */
#region ExportDataSource 导出数据集
/// <summary>
/// 导出数据集
/// </summary>
/// <param name="ds">数据集</param>
/// <param name="fileName">文件名</param>
public static void ExportDataSource(DataSet ds,string filePath)
{
if (ds == null || ds.Tables.Count==0)
{
return;
}
var _type = GetExcelType(filePath);
var _workbook = CerateWorkbook(_type);
DataTable _dt;
// 循环遍历表
for (var tableIndex = 0;tableIndex < ds.Tables.Count;tableIndex++)
{
_dt = ds.Tables[tableIndex];
CreateSheet(_workbook,_dt);
}
//转为字节数组
var _stream = new MemoryStream();
_workbook.Write(_stream);
var _buf = _stream.ToArray();
//保存为Excel文件
using (var fs = new FileStream(filePath,FileMode.Create,FileAccess.Write))
{
fs.Write(_buf,0,_buf.Length);
fs.Flush();
}
}
#endregion
#region ExportDataTable 导出数据表
/// <summary>
/// 导出数据表
/// </summary>
/// <param name="ds">数据表</param>
/// <param name="fileName">文件名</param>
public static void ExportDataTable(DataTable dt,string filePath)
{
if (dt==null)
{
return;
}
var _type = GetExcelType(filePath);
var _workbook = CerateWorkbook(_type);
// 循环遍历表
CreateSheet(_workbook,dt);
//转为字节数组