public ActionResult ImportExcel()
{
try
{
int sheetIndex = 0;
int headerRowIndex = 0;
DataTable table = new DataTable();
if (Request.ContentLength > 2 * 1024 * 1024)
{
return ExtjsFormFail("上¦?传ä?文?件t太¬?大䨮了¢?!ê?");
}
HttpPostedFileBase postedFile = Request.Files["file"];//从䨮前¡ã台¬¡§获?取¨?文?件t
if (postedFile != null)
{
//判D断?文?件t扩¤?展1名?是º?否¤?正y确¨¡¤
string fileExtension = Path.GetExtension(Path.GetFileName(postedFile.FileName));
if (fileExtension == null || fileExtension.ToLower() != ".xls")//&& fileExtension != ".xlsx" 目?前¡ã.Net不?支¡ì持?Execl2007
{
return ExtjsFormFail("请?上¦?传ä?正y确¨¡¤的Ì?文?件t格?式º?:êoxls!ê?");
}
//存ä?到Ì?系¦Ì统ª3临¢¨´时º¡À文?件t夹D下?
string filePath = Path.GetTempFileName();
postedFile.SaveAs(filePath);//上¦?传ä?文?件t
FileStream readStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
HSSFWorkbook workbook = new HSSFWorkbook(readStream);
HSSFSheet sheet = workbook.GetSheetAt(sheetIndex);
HSSFRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
bool hand = true;
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
for (int k = 0; k < table.Columns.Count; k++)
{
if (column.ToString() == table.Columns[k].Caption)
{
hand = false;
}
}
if (hand)
{
table.Columns.Add(column);
}
else
{
DataColumn column1 = new DataColumn(column + i.ToString());
table.Columns.Add(column1);
}
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
HSSFRow 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);
}
}
else
{
return ExtjsFormFail("请?选?择?您¨²要°a导Ì?入¨?的Ì?文?件t");
}