1
\$\begingroup\$

I want to read data from excel. I made this class:

public class Excel
{
    string path = "";
    _Application excel = new _Excel.Application();
    Workbook wb;
    Worksheet ws;
    public Excel(string path, int Sheet)
    {
        this.path = path;
        wb = excel.Workbooks.Open(path);
        ws = wb.Worksheets[Sheet];
    }

    public string ReadCell(int i, int j)
    {
        i++;
        j++;
        if (ws.Cells[i, j].Value2 != null)
        {
            try
            {
                double s = ws.Cells[i, j].Value2;
                string result = s.ToString();
                return result;
            }
            catch (Exception)
            {
                return ws.Cells[i, j].Value2;
            }

        }
        else
        {
            return "";
        }
    }
}

This code works well, but it is very slow. I need to read about 1000 cells and it tooks mins...Is there any way how to do fast?

\$\endgroup\$

migrated from stackoverflow.com Dec 23 '17 at 2:40

This question came from our site for professional and enthusiast programmers.

  • 1
    \$\begingroup\$ Often faster to object iAmA2DArray = ws.GetRange("A1", "Z99"); then loop over the native array. \$\endgroup\$ – Alex K. Dec 20 '17 at 17:24
  • \$\begingroup\$ Another much faster alternative is to connect to the worksheet using ADO.NET. \$\endgroup\$ – Zev Spitz Dec 20 '17 at 17:25
  • \$\begingroup\$ Your whole if-else could be replace by return ws.Cells[i, j].Value2?.ToString() ?? ""; \$\endgroup\$ – Magnetron Dec 20 '17 at 17:40
  • \$\begingroup\$ Also, drop the Interop. Personally, I like EPPlus. Also this appears to be a duplicate: Slow Performance When Reading Excel \$\endgroup\$ – Magnetron Dec 20 '17 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy