[英]C# Web Api - Upload and Read data from excel file without saving the file
我有一個WebApi,它將收到用戶作為multipart / form-data上傳的excel文件。 我需要讀取該文件的內容才能更新數據庫。 我在考慮使用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");
}
您可以使用Microsoft.Interop.Excel來讀取xls文件,但即使是微軟也不贊成這種技術,因為它很慢並且不能在服務器上運行。 此外,他們的支持剛剛結束。
作為替代方案,您可以使用EasyXLS庫。 您可以使用它來讀取XLS文件。
看一下這個代碼示例,它解釋了如何將Excel文件導入SQL表: http : //www.easyxls.com/manual/FAQ/import-excel-to-sql.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.