using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
namespace ConsoleApp2
{
public static class ExcelHelper
{
/// <summary>
/// 读取excel 到datatable
/// 默认第一行为表头,导入第一个工作表
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ExcelToDataTable(string strFileName)
{
DataTable dt = new DataTable();
FileStream file = null;
IWorkbook Workbook = null;
try
{
using (file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))//C#文件流读取文件
{
if (strFileName.IndexOf(".xlsx") > 0)
//把xlsx文件中的数据写入Workbook中
Workbook = new XSSFWorkbook(file);
else if (strFileName.IndexOf(".xls") > 0)
//把xls文件中的数据写入Workbook中
Workbook = new HSSFWorkbook(file);
if (Workbook != null)
{
ISheet sheet = Workbook.GetSheetAt(0);//读取第一个sheet
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
//得到Excel工作表的行
IRow headerRow = sheet.GetRow(0);
//得到Excel工作表的总列数
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
//得到Excel工作表指定行的单元格
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
if (row.FirstCellNum < 0)
continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
}
return dt;
}
}
catch (Exception ex)
{
if (file != null)
{
file.Close();//关闭当前流并释放资源
}
return null;
}
}
}
原文:https://www.cnblogs.com/b2cup/p/14813078.html