Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI
I want to display data on an excel spreadsheet in DataGridView please am using C#.
Posted

 
Share this answer
 
I used this a long time back in my project, maybe it will help:

C#
public ArrayList ProcessWorkbook(string filePath)
        {
            string file = filePath;

            Excel.Application excel = null;
            Excel.Workbook wkb = null;
            ArrayList al = new ArrayList();
            try
            {
                excel = new Excel.Application();

                wkb = ExcelTools.OpenBook(excel, file, false, true, false);

                Excel.Worksheet sheet = wkb.Sheets["Adresses"] as Excel.Worksheet;

                Excel.Range range = null;

                if (sheet != null)
                    range = sheet.get_Range("A1:X6702", Missing.Value);


                if (range != null)
                {
                    foreach (Excel.Range r in range)
                    {
                        al.Add(r.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                //if you need to handle stuff
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (wkb != null)
                    ExcelTools.ReleaseRCM(wkb);

                if (excel != null)
                    ExcelTools.ReleaseRCM(excel);
            }
            return al;
        }

//----------------
    public static class ExcelTools
    {
        public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly, bool editable,
        bool updateLinks)
        {
            Excel.Workbook book = excelInstance.Workbooks.Open(
                fileName, updateLinks, readOnly,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
            return book;
        }

        public static void ReleaseRCM(object o)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
            }
            catch
            {
            }
            finally
            {
                o = null;
            }
        }
    }
 
Share this answer
 
Comments
fjdiewornncalwe 2-Feb-13 11:10am    
Plagiarized from Source and OP makes a blatant claim that it's his own.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900