0

I have VS Express 2015 installed and MS office 2007 on my pc. I need to read some values from an excel sheet. I added Microsoft Office 12.0 Object Library but I can't use this

using Microsoft.Office.Interop.Excel;

I get the following error : The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' (are you missing an assembly reference?)

Manick9
  • 137
  • 2
  • 10
  • 1
    I frequently use Interop Excel, so here is the Reference I added in order to get it: `C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll`. Another way is to find Microsoft Excel Object Library, according to [Cannot find Microsoft.Office.Interop Visual Studio](http://stackoverflow.com/a/21986486/6741868). – Keyur PATEL Sep 20 '16 at 02:15
  • I can't find this C:\Windows\assembly\GAC_MSIL – Manick9 Sep 20 '16 at 02:45
  • 1
    Then try following the instructions from the link. That should work for your case. – Keyur PATEL Sep 20 '16 at 02:55
  • Is there any other workaround? I will install those .dll and Office Tools for VS2015 and try. – Manick9 Sep 20 '16 at 03:36
  • 1
    Try these: [2007 Microsoft Office System Update: Redistributable Primary Interop Assemblies](https://www.microsoft.com/en-us/download/details.aspx?id=18346) – Keyur PATEL Sep 20 '16 at 03:46

1 Answers1

1

As you are looking to read some values from an excel sheet EPPlus is grate and easy way to work with Excel file. This is a wrapper for Open office XML.

public static DataTable getDataTableFromExcel(string path)
{
    using (var pck = new OfficeOpenXml.ExcelPackage())
    {
        using (var stream = File.OpenRead(path))
        {
            pck.Load(stream);
        }
        var ws = pck.Workbook.Worksheets.First();  
        DataTable tbl = new DataTable();
        bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            var row = tbl.NewRow();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
            tbl.Rows.Add(row);
        }
        return tbl;
    }
}