我有一个WebApi,它会收到用户上传的excel文件,作为multipart / form-data。 我需要读取该文件的内容才能更新数据库。我在考虑使用EPPlus,但我无法访问该文件。 这是代码
public class MyController : APIController
{
[Route("import")]
[HttpPost]
public async Task<HttpResponseMessage> importFile()
{
if (!Request.Content.IsMimeMultipartContent())
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "ERROR");
Stream stream = await Request.Content.ReadAsStreamAsync();
var excel = new ExcelPackage(stream);
var workbook = excel.Workbook;
var sheet = excel.Workbook.Worksheets.First();
...
}
错误发生在var sheet = excel.Workbook.Worksheets.First()
上,因为工作簿没有任何工作表(但物理文件有2个)。
我做错了什么?是流吗?
我正在尝试为每种类型的Excel文件(.xls或.xlsx)设置单独的库,但我无法使用.xls文件。 我正在使用ExcelDataReader,代码现在是这样的:
public async Task<HttpResponseMessage> importFile()
{
if (!Request.Content.IsMimeMultipartContent())
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "NOT MULTIPART");
Stream stream = await Request.Content.ReadAsStreamAsync();
//open xlsx file
var excel = new ExcelPackage(stream);
var workbook = excel.Workbook;
try
{
var sheet = excel.Workbook.Worksheets.First();
//working fine with EPPlus for .xlsx files
return Request.CreateResponse(HttpStatusCode.OK, errors);
}catch(Exception)//open xls file
{
//if its a .xls file it will throw an Exception
}
//using ExcelDataReader to open .xls file
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
// the DataSet is null, stream is setted as ReadOnlyStream and stream.length is throwing an ObjectDisposedException
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "erro");
}
答案 0 :(得分:1)
您可以使用Microsoft.Interop.Excel来读取xls文件,但即使是微软也不赞成这种技术,因为它很慢并且不能在服务器上运行。此外,他们的支持刚刚结束。
作为替代方案,您可以使用EasyXLS库。您可以使用它来读取XLS文件。
看一下这个代码示例,它解释了如何将Excel文件导入SQL表: http://www.easyxls.com/manual/FAQ/import-excel-to-sql.html