public ActionResult ImportExcel()
{
string messages = string.Empty;
bool isSuccess = false;
try
{
HttpPostedFileBase file = Request.Files[0];//接收客户端传递过来的数据.
if (file == null)
{
messages = "请上传Excel文件";
return Content("{\"IsSuccess\":\"" + isSuccess + "\",\"Message\":\"" + messages + "\"}", "text/plain");
}
else
{
//对文件的格式判断,此处省略
List ownerList = new List();
Stream inputStream = file.InputStream;
//HSSFWorkbook hssfworkbook = new HSSFWorkbook(inputStream);
XSSFWorkbook hssfworkbook = new XSSFWorkbook(inputStream);
NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
// IRow headerRow = sheet.GetRow(0);//第一行为标题行
// int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
InOwnerVO owner = new InOwnerVO();
if (row != null)
{
if (row.GetCell(0) != null)
{
owner.Name = GetCellValue(row.GetCell(0));
}
if (row.GetCell(1) != null)
{
owner.Tel = GetCellValue(row.GetCell(1));
}
if (row.GetCell(2) != null)
{
owner.StoreNo = GetCellValue(row.GetCell(2));
}
if (row.GetCell(3) != null)
{
owner.HouseNo = GetCellValue(row.GetCell(3));
}
}
ownerList.Add(owner);
}
OwnerManager manager = new OwnerManager();
isSuccess = manager.ImportOwner(ownerList);
if (isSuccess)
{
messages = "导入成功!";
}
return Content("{\"IsSuccess\":\"" + isSuccess + "\",\"Message\":\"" + messages + "\"}", "text/plain");
//return Content("导入成功");
}
}
catch (Exception e)
{
messages = "导入失败!";
return Content("{\"IsSuccess\":\"" + isSuccess + "\",\"Message\":\"" + messages + "\"}", "text/plain");
//return Content("导入失败");
}
}
///
/// 根据Excel列类型获取列的值
///
/// Excel列
///
private static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
case CellType.Unknown:
default:
return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
}