private static DataTable ExcelToDataSet(string path)
{
try
{
DataTable dt = new DataTable();
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
if (sheet != null)
{
HSSFRow firstRow = (HSSFRow)sheet.GetRow(1);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
HSSFCell cell = (HSSFCell)firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
dt.Columns.Add(column);
}
}
}
//最后一行的标号
int rowCount = sheet.LastRowNum;
for (int i = 2; i <= rowCount; ++i)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = dt.NewRow();
int m = 0;
if (row.FirstCellNum < 0)
{
continue;
}
for (int j = row.FirstCellNum; j < cellCount; j++)
{
DateTime resultTime;
if (row.GetCell(j) != null && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{//同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
else
{
dataRow[j] = "";
m++;
}
}
if (m < cellCount)
{
dt.Rows.Add(dataRow);
}
}
}
}
return dt;
}
catch (Exception ex)
{
return null;
}
}