jquery - 如何从ajax读取excel到web api
问题描述
这是我的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。将感谢您的帮助。
解决方案
首先,要上传文件,您可以使用带有如下代码的视图:
@section scripts
{
<script type="text/javascript">
$(document).ready(function() {
$('#upload').click(function () {
var data = new FormData();
var file = $('form input[type=file]')[0].files[0];
data.append('file',file);
$.ajax({
url: '/api/excels/Upload',
processData: false,
contentType: false,
data: data,
type: 'POST'
}).done(function(result) {
alert(result);
}).fail(function(a, b, c) {
console.log(a, b, c);
});
});
});
</script>
}
其次,要接收数据和破解,改变方法如下:
public class ExcelsController : ApiController
{
[HttpPost]
public async Task<string> Upload()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
// extract file name and file contents
Stream stream = new MemoryStream(await provider.Contents[0].ReadAsByteArrayAsync());
//get fileName
var filename = provider.Contents[0].Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
//Check file type
if (filename .EndsWith(".xls"))
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (filename .EndsWith(".xlsx"))
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
return "Not Valid";
}
var result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
return result;
}
}
推荐阅读
- r - 列出给定函数内的所有函数
- jenkins - 詹金斯管道脚本的问题。没有方法签名适用于参数类型:(java.lang.String) values[string]
- angular - Angular2 单元测试
- websocket - 关于 IE 中 websocket 数量限制的解决方法
- sql - 一个帐号与两个不同的 CIN 关联且两个 CIN 的后四位应相同的搜索表
- angular - 具有响应式表单的自定义控件
- php - 优化模型查询
- c# - 如何在winform janus网格中专注于过滤器行的一列
- ionic-framework - 在 ionic v4 中添加自定义加载微调器
- java - 从 selenium 服务器获取所有会话