/// <summary>
/// 上传excel文件 并将文件数据导入到数据库
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
public JsonResult UploadFile(HttpPostedFileBase file)
{
var fileName = file.FileName;
fileName = fileName.Replace(" ", "_").Replace("\", "_").Replace("/", "_");
fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;
var defaultPath = AppSettings["UploadFiles"];
if (String.IsNullOrWhiteSpace(defaultPath))
defaultPath = @"D:RegTechUploadFiles";
var excelUploadPath = Path.Combine(defaultPath, "UserCustomBlackList");
if (!Directory.Exists(excelUploadPath))
Directory.CreateDirectory(excelUploadPath);
// 将上传文件保存到服务器
var saveFilePath = Path.Combine(excelUploadPath, fileName);
file.SaveAs(saveFilePath);
List<UserCustomBlackList> excelResult = ReadExcelByCustomBlack(saveFilePath);
}
/// <summary>
/// 将上传的Excel数据导入到数据库中
/// </summary>
/// <param name="fileName"></param>
/// <param name="type"></param>
/// <returns></returns>
protected List<UserCustomBlackList> ReadExcelByCustomBlack(String fileName)
{
List<UserCustomBlackList> rtn = new List<UserCustomBlackList>();
FileInfo existingFile = new FileInfo(fileName);
try
{
using (FileStream fs = System.IO.File.OpenRead(fileName))
{
// 根据文件创建Excel WorkBook
IWorkbook wk = WorkbookFactory.Create(fs);
string extension = fileName.Substring(fileName.LastIndexOf(".")).ToString().ToLower();
// 获取第一个Sheet页
ISheet sheet = wk.GetSheetAt(0);
int rowIndex = 1;
for (int i = 1; i <= sheet.LastRowNum; i++)
{
UserCustomBlackList data = new UserCustomBlackList();
IRow row = sheet.GetRow(i);
if (row != null)
{
data.DisplayIndex = rowIndex++;
data.BlackContent = row.GetCell(0) == null ? String.Empty : row.GetCell(0).ToString();
}
if (!string.IsNullOrWhiteSpace(data.BlackContent))
rtn.Add(data);
}
return rtn;
}
}
catch (Exception ex)
{
LogUtility.Exception(ex,source: "客户端-ReadExcelByCustomBlack");
return null;
}
}