.net匯入excel檔案到dataset
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檔案路徑“);