27,580
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;
using System.Configuration;
using NPOI.HSSF.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
namespace Util
{
/// <summary>
/// NPOI辅助类,add by ngye, on 2014-08-26.
/// </summary>
public static class NPOIHelper
{
/// <summary>
/// 根据路径,得到所有的 Sheet , 以及每个Sheet 第一行的表头
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static Dictionary<string, List<string>> GetAllSheetsWithHeader(string filePath)
{
Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
IWorkbook workbook = GetWorkBook(filePath); //获取到工作簿
ISheet sheet = null;
for (int i = 0; i < workbook.NumberOfSheets; i++)
{
//获取到 Sheet 名
string sheetName = workbook.GetSheetName(i);
sheet = workbook.GetSheetAt(i);
List<string> colNameList = new List<string>();
if (sheet != null)
{
//得到第一行
IRow firstRow = sheet.GetRow(0);
if (firstRow == null)
continue;
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
for (int j = firstRow.FirstCellNum; j < cellCount; ++j)
{
string colName = firstRow.GetCell(j).StringCellValue;
colNameList.Add(colName);
}
}
result.Add(sheetName, colNameList);
}
workbook.Clear();
return result;
}
/// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="sheetIndex">Sheet序号</param>
/// <returns>DataTable</returns>
public static DataTable ImportExcelFile(string filePath, int sheetIndex)
{
IWorkbook workbook = GetWorkBook(filePath);
ISheet sheet = null;
DataTable dt = new DataTable();
int startRow = 0;
try
{
sheet = workbook.GetSheetAt(sheetIndex);
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);
dt.Columns.Add(column);
}
startRow = sheet.FirstRowNum + 1;
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = dt.NewRow();
int dataColumn = 0;
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null){ //同理,没有数据的单元格都默认是null
Cell2DataRow(dataRow, row, j);
//如果对应行的列不为NULL, 而且
if (!dataRow.IsNull(j) && !string.IsNullOrEmpty(Convert.ToString(dataRow[j])))
{
dataColumn++;
}
}
}
//只要有一列有数据,就应该加入
if (dataColumn != 0)
{
dt.Rows.Add(dataRow);
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 根据 Excel 文件路径获取 IWorkbook
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static IWorkbook GetWorkBook(string filePath)
{
GC.Collect();
IWorkbook workbook = null;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (filePath.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (filePath.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
fs.Close();
fs.Dispose();
GC.Collect();
return workbook;
}
/// <summary>
/// Excel 单元格转成 DataRow
/// </summary>
/// <param name="dr"></param>
/// <param name="row"></param>
/// <param name="j"></param>
public static void Cell2DataRow(DataRow dr, IRow row, int j)
{
ICell cell = row.GetCell(j);
switch (cell.CellType)
{
case CellType.Blank:
dr[j] = DBNull.Value;
break;
case CellType.Boolean:
dr[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
dr[j] = cell.DateCellValue;
}
else
{
dr[j] = cell.NumericCellValue;
}
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Error:
dr[j] = cell.ErrorCellValue;
break;
case CellType.Formula:
//cell = evaluator.EvaluateInCell(cell) as ICell;
dr[j] = cell.ToString();
break;
default:
throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
}
}
}//end of class
}//end of namespace