基本信息
源码名称:通过NPOI读取Excel数据到DataTable
源码大小:22.36M
文件格式:.zip
开发语言:C#
更新时间:2021-06-23
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
通过NPOI库,使用C#来读取excel数据
public static DataTable ExcelToTable(string file, ref List<string> typeList)
{
DataTable dt = new DataTable();
List<IComparable> rowList = new List<IComparable>();
IWorkbook workbook = null;
string fileExt = Path.GetExtension(file).ToLower();
using(FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
if (fileExt == ".xlsx")
{
workbook = new XSSFWorkbook(fs);
}
else if (fileExt == ".xls")
{
workbook = new HSSFWorkbook(fs);
}
if (workbook == null)
{
return null;
}
ISheet sheet = workbook.GetSheetAt(0);
//表头
IRow header = sheet.GetRow(0);
for (int i = 0; i < header.LastCellNum; i )
{
ICell cell = header.GetCell(i);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
{
dt.Columns.Add(cell.ToString());
//Console.WriteLine(cell.ToString());
}
}
// 数据内容
for (int i = (sheet.FirstRowNum 1); i <= sheet.LastRowNum; i )
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < header.LastCellNum; j )
{
if (row.GetCell(j) != null)
{
if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
try
{
rowList.Add(row.GetCell(j).NumericCellValue);
//Console.WriteLine("获取数值");
if (i == 1)
{
typeList.Add("Number");
}
}
catch
{
rowList.Add(row.GetCell(j).ToString());
//Console.WriteLine("获取字符串");
if (i == 1)
{
typeList.Add("String");
}
}
}
}
}
if (rowList.Count > 0)
{
dt.Rows.Add(rowList.ToArray());
rowList.Clear();
}
}
}
return dt;
}