码迷,mamicode.com
首页 > Web开发 > 详细

.net导入excel文件到dataset

时间:2018-12-09 13:55:57      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:return   wro   table   excel   方法   win   需要   try   null   

1.需要引入:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

//2007及以上版本
XSSFWorkbook xWorkbook=new XSSFWorkbook(fileStream);
//2003版本
HSSFWorkbook hWorkbook=new HSSFWorkbook(fileStream);

2.传入文件路径,返回dataset数据集合

public static DataSet ImportExcel(string filePath)
{
DataSet ds = null;
try
{
FileStream fileStream = new FileStream(filePath, FileMode.Open);
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
ISheet sheet = null;
IRow row = null;
ds = new DataSet();
DataTable dt = null;
for (int i = 0; i < workbook.Count; i++)
{
dt = new DataTable();
dt.TableName = "table" + i.ToString();
//获取sheet表
sheet = workbook.GetSheetAt(i);
//起始行索引
int rowIndex = sheet.FirstRowNum;
//获取行数
int rowCount = sheet.LastRowNum;
//获取第一行
IRow firstRow = sheet.GetRow(rowIndex);
//起始列索引
int colIndex = firstRow.FirstCellNum;
//获取列数
int colCount = firstRow.LastCellNum;
DataColumn dc = null;
//获取列数
for (int j = colIndex; j < colCount; j++)
{
dc = new DataColumn(firstRow.GetCell(j).StringCellValue);
dt.Columns.Add(dc);
}
//跳过第一行列名
rowIndex++;
for (int k = rowIndex; k <= rowCount; k++)
{
DataRow dr = dt.NewRow();
row = sheet.GetRow(k);
for (int l = colIndex; l < colCount; l++)
{
if (row.GetCell(l) == null)
{
continue;
}
else {
row.GetCell(l).SetCellType(CellType.String);
//stuUser.setPhone(row.getCell(0).getStringCellValue());
dr[l] = row.GetCell(l).StringCellValue;
}
//dr[l] = row.GetCell(l).StringCellValue;

}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
}
sheet = null;
workbook = null;
fileStream.Close();
fileStream.Dispose();
}
catch (Exception ex)
{
throw;
}
return ds;
}

3.调用方法:

DataSet ds = ImportExcel(“excel文件路径“);

 

.net导入excel文件到dataset

标签:return   wro   table   excel   方法   win   需要   try   null   

原文地址:https://www.cnblogs.com/lymkpds/p/9108146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!