/// <summary>
/// EXCEL转DataTable
/// </summary>
/// <param name="postedfile">上传的文件对象</param>
/// <returns>返回一张table</returns>
static FileStream stream;
static DataTable table;
public static object obj = new object();
public static DataTable ImportExcelToDataTable(HttpPostedFile postedfile)
{
lock (obj)
{
if (postedfile != null)
{
try
{
string filename = DateTime.Now.ToString("yyyyMMddhhssmmffffff") + Path.GetExtension(postedfile.FileName);
string fullpath = HttpContext.Current.Server.MapPath("~/AdminSystem/TempFiles/");
if (!Directory.Exists(fullpath))
{
Directory.CreateDirectory(fullpath);
}
fullpath += filename;
postedfile.SaveAs(fullpath);


table = new DataTable();
stream = File.Open(fullpath, FileMode.Open, FileAccess.Read);


XSSFWorkbook workbook = new XSSFWorkbook(stream);
ISheet sheet = workbook.GetSheetAt(0);
//获取sheet的首行
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
table.Rows.Add(dataRow);
}
stream.Close();
File.Delete(fullpath);
return table;
}
catch
{
table.Dispose();
return null;
}
finally
{
stream.Close();
table.Dispose();
}
}
else
{
return null;
}
}
}