1

I'm developing an ASP.NET MVC C# Application to take data from excel file and extract info from it to replace an Email Template that user created. But I see in many results I search the method so complicated and long. I would like to know the most simply want to take data from excel file. For example, my mail template has a placeholder and I would like to extract the data from Distributor column and create a list of mail based on the excel file, how many rows does it have.

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17

2 Answers2

1

Do not use interop in Server environment:

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment. Source: Microsoft note.

Check out this library - ExcelDataReader. It is fast and reliable and definitely not requires much code.

Ivvan
  • 720
  • 11
  • 25
0

A sample code:

public string excelParsing(string fullpath)
{
    string data = "";
    //Create COM Objects. Create a COM object for everything that is referenced
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullpath);
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

    int rowCount = xlRange.Rows.Count;
    int colCount = xlRange.Columns.Count;

    //iterate over the rows and columns and print to the console as it appears in the file
    //excel is not zero based!!
    for (int i = 1; i <= rowCount; i++)
    {
        for (int j = 1; j <= colCount; j++)
        {
             //either collect data cell by cell or DO you job like insert to DB 
            if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                data += xlRange.Cells[i, j].Value2.ToString();
        }
    }

    return data;
}

For detail description : http://sforsuresh.in/how-to-read-an-excel-file-using-asp-net-mvc4/

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90