这是我的ajax调用:
$.ajax({
type: "POST",
url: "/api/excels/Upload",
data: $file,
contentType: false,
processData: false
}).done(function (result) {
alert(result);
}).fail(function (a, b, c) {
console.log(a, b, c);
});
return false;// if it's a link to prevent post
});
这是我的 Web APi 控制器功能:
[HttpPost]
public async Task<string> Upload()
{
FilePath filePath = "HOW SHOULD I GET THE FILE???";
FileStream stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = null;
//Check file type
if (filePath.EndsWith(".xls"))
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (filePath.EndsWith(".xlsx"))
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
var result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
String sheetName = result.Tables[0].TableName;
}
如您所见,我正在使用 ExcelReader 获取文件并对其进行解析以读取其内容。我的最终目标是使用实体框架读取每一行并将每一行保存在数据库中。我也不能使用 Form 来访问该文件,因为它是 Web Api。将感谢您的帮助。