此文爲了實現將Excel數據導入DataTable中展示,不過有一些弊端,暫時不支持複雜格式的Excel導入。 這是個完整的類,添加相應的.dll可直接使用。
/***********************
Author: Tst
CSDN bolg: Ricardo.M.Tan
***********************/
using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
namespace Chn.gzGISer.NPOIHelper
{
/// <summary>
/// 將Excel數據加載到DataTable中
/// </summary>
public class NPOILoadToDataTable
{
private static IWorkbook workBook = null;
private static FileStream fs = null;
/// <summary>
/// 將excel中的數據導入到DataTable中
/// </summary>
/// <param name="fileName">excel工作薄文件路徑</param>
/// <param name="sheetName">excel工作薄sheet的名稱</param>
/// <param name="isFirstRowColumn">是否將第一行是設爲DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public static DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0)
{
workBook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > 0)
{
workBook = new HSSFWorkbook(fs);
}
if (sheetName != null)
{
sheet = workBook.GetSheet(sheetName);
if (sheet == null)
{
sheet = workBook.GetSheetAt(0);
}
}
else
{
sheet = workBook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum;
}
else
{
startRow = sheet.FirstRowNum + 1;
}
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null)
{
continue;
}
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
}
}
data.Rows.Add(dataRow);
}
}
}
catch (Exception)
{
throw;
}
finally
{
fs.Dispose();
}
return data;
}
}
}