Imports
using Excel = Microsoft.Office.Interop.Excel;
I need to upload an excel file and convert it to a list in code
below is the method it calls when uploading a file from the front
(I'm trying to write it on some free library)
here i put excel from user interface
<form method="post" asp-controller="ImportExcel" asp-action="ImportCommEnding" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit">Import from Excel</button>
</form>
public async Task<List<CommunicationEnding>> ImportExcel(IFormFile file)
{
var list = new List<CommunicationEnding>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
Excel.Application excel = new Excel.Application();
Excel.Workbook wb = new Excel.Workbook();
//here I want convert stream to excel
//
//
//
Excel.Worksheet worksheet = excel.ActiveSheet as Excel.Worksheet;
var rowcount = worksheet.Rows; // dont work
for(int row = 2; row <= rowcount; row++)
{
list.Add(new CommunicationEnding
{
Id = row,
ContractNumber = worksheet.Cells[row, 1].ToString().Trim(),
ItemName = worksheet.Cells[row, 2].ToString().Trim(),
RegistrationNo = worksheet.Cells[row, 3].ToString().Trim(),
DateExpire = Convert.ToDateTime(worksheet.Cells[row, 4].ToString().Trim()),
});
}
// here i want to return list from column from excel
return list;
I don't know how to convert stream to Excel.Workbook();and how to count rows