ExcelHelper
来源:互联网 发布:c语言书籍 知乎 编辑:程序博客网 时间:2024/05/17 13:06
using System;
using System.Data;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Collections;
using System.Reflection;
/*
* Excel操作帮助类
* NPOI控件
* 2010年11月3日
* William
*/
namespace Common
{
public class ExcelHelper
{
public static ExcelHelper Instance = new ExcelHelper();
private ExcelHelper() { }
HSSFWorkbook hssfworkbook;
/// <summary>
/// 将Excel文件转换成DataTable
/// </summary>
/// <param name="path">Excel文件路径</param>
/// <returns>DataTable</returns>
public DataTable ConvertToDataTable(string path)
{
if (string.IsNullOrEmpty(path))
return null;
if (!File.Exists(path))
return null;
this.InitializeWorkbook(path);
return this.ConvertToDataTable();
}
public string ConvertToExcel(DataTable dt)
{
return null;
}
/// <summary>
/// 初始化工作簿
/// </summary>
/// <param name="path"></param>
private void InitializeWorkbook(string path)
{
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
/// <summary>
/// 转换成DataTable
/// </summary>
private DataTable ConvertToDataTable()
{
HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
if (!rows.MoveNext())
return null;
//DataTable ColumnName
HSSFRow row = (HSSFRow)rows.Current;
for (int i = 0; i < row.LastCellNum; i++)
{
DataColumn col = new DataColumn();
HSSFCell cell = row.GetCell(i);
if (cell == null)
{
col.ColumnName = null;
dt.Columns.Add(col);
}
else
{
col.ColumnName = cell.ToString();
dt.Columns.Add(col);
}
}
//DataTable内容
while (rows.MoveNext())
{
row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
return dt;
}
/// <summary>
/// 导出列名
/// </summary>
public System.Collections.Generic.Dictionary<string,string> ListColumnsName;
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public void ExportExcel(DataTable dtSource, string filePath)
{
if (ListColumnsName == null || ListColumnsName.Count == 0)
throw (new Exception("请对ListColumnsName设置要导出的列明!"));
HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(dtSource, excelWorkbook);
SaveExcelFile(excelWorkbook, filePath);
}
/// <summary>
/// LIST导出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public void ExportExcel(IList lstSource, string filePath)
{
if (ListColumnsName == null || ListColumnsName.Count == 0)
throw (new Exception("请对ListColumnsName设置要导出的列明!"));
HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(lstSource, excelWorkbook);
SaveExcelFile(excelWorkbook, filePath);
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public void ExportExcel(DataTable dtSource, Stream excelStream)
{
if (ListColumnsName == null || ListColumnsName.Count == 0)
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 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 void SaveExcelFile(HSSFWorkbook excelWorkBook, Stream excelStream)
{
try
{
excelWorkBook.Write(excelStream);
}
finally
{
}
}
/// <summary>
/// 创建Excel文件
/// </summary>
/// <param name="filePath"></param>
protected HSSFWorkbook CreateExcelFile()
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
return hssfworkbook;
}
/// <summary>
/// 创建excel表头
/// </summary>
/// <param name="dgv"></param>
/// <param name="excelSheet"></param>
protected void CreateHeader(HSSFSheet excelSheet)
{
int cellIndex = 0;
//循环导出列
foreach (System.Collections.Generic.KeyValuePair<string,string> de in ListColumnsName)
{
HSSFRow newRow = excelSheet.CreateRow(0);
HSSFCell newCell = newRow.CreateCell(cellIndex);
newCell.SetCellValue(de.Value.ToString());
cellIndex++;
}
}
/// <summary>
/// 插入数据行
/// </summary>
protected void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
{
int rowCount = 0;
int sheetCount = 1;
HSSFSheet newsheet = null;
//循环数据源导出数据集
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
foreach (DataRow dr in dtSource.Rows)
{
rowCount++;
//超出10000条数据 创建新的工作簿
if (rowCount == 10000)
{
rowCount = 1;
sheetCount++;
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
}
HSSFRow newRow = newsheet.CreateRow(rowCount);
InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook);
}
}
/// <summary>
/// LIST插入数据行
/// </summary>
protected void InsertRow(IList lstSource, HSSFWorkbook excelWorkbook)
{
int rowCount = 0;
int sheetCount = 1;
HSSFSheet newsheet = null;
//循环数据源导出数据集
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
foreach(Object obj in lstSource)
{
rowCount++;
if (rowCount == 10000)
{
rowCount = 1;
sheetCount++;
newsheet = excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
}
HSSFRow newRow = newsheet.CreateRow(rowCount);
InsertCell(lstSource, obj, 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 void InsertCell(DataTable dtSource, DataRow drSource, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
{
for (int cellIndex = 0; cellIndex < ListColumnsName.Count; cellIndex++)
{
//列名称
//string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
ArrayList keys = new ArrayList(ListColumnsName.Keys);
string columnsName = keys[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 = 0;
int.TryParse(drValue, out intV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(intV.ToString());
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
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() + ":类型数据无法处理!"));
}
}
}
/// <summary>
/// list导出数据行
/// </summary>
/// <param name="dtSource"></param>
/// <param name="drSource"></param>
/// <param name="currentExcelRow"></param>
/// <param name="excelSheet"></param>
/// <param name="excelWorkBook"></param>
protected void InsertCell(IList lstSource, Object obj, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
{
for (int cellIndex = 0; cellIndex < ListColumnsName.Count; cellIndex++)
{
//列名称
//string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
ArrayList keys = new ArrayList(ListColumnsName.Keys);
string columnsName = keys[cellIndex].ToString();
HSSFCell newCell = null;
//反射获取实体类字段信息
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(columnsName);
System.Type rowType = info.PropertyType;
object tempObject = info.GetValue(obj,null);
string drValue = "";
if (tempObject != null)
{
drValue = tempObject.ToString();
}
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 = 0;
int.TryParse(drValue, out intV);
newCell = currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(intV.ToString());
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
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 -1;
}
}
}
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper
- ExcelHelper.cs
- ExcelHelper 4
- ExcelHelper 6
- C# ExcelHelper类
- C#ExcelHelper操作类
- Excel操作工具类ExcelHelper
- C# Excel操作类 ExcelHelper
- 数据导入到EXCEL(EXCELHelper)
- C# Excel操作类ExcelHelper
- 通过Android系统日志监听程序启动事件
- 网络流 1024
- 立体视觉算法-SGBM(一)
- 【多线程】_线程生命周期笔记
- tmpfs文件系统
- ExcelHelper
- FFMEG开发教程--(03)ffmpeg播放声音
- mongodb连接池管理机制
- 动态语言和静态语言的比较
- Collection框架
- FFMEG开发教程--(04)ffmpeg进程播放
- 【包及访问控制权限】_包的定义及导入笔记
- (小数)javascript(js)的小数点乘法除法问题
- ArrayList扩容引起效率降低问题的原理