Import excel sheet data to datagrid without using oledb

前端 未结 3 543
日久生厌
日久生厌 2021-01-29 11:19

In my Windows based application(C#) i want to import excel sheet to show its data in DatatGridView i dont want to use oledb

any Help

相关标签:
3条回答
  • 2021-01-29 11:41

    I'm late to the party, but I have something worthwhile to add! I tried Juan's code and it didn't compile out-of-the-box. I modified it a little bit after researching the internet for a few more hours and got it to do exactly what the original poster asked (as I needed to do the same thing). I had to piece code together from other sources, and unfortunately, I did not keep track of what bits and pieces I tried and changed so I can't comment much about it.

    The following code works in Visual Studio 2008 with .NET 3.5. Also, the formatting is lost when the data is put into the array (for example, dates become doubles which require a conversion with DateTime.FromOADate() to change it back). The issue with that is you can't tell if a value is an actual double or a date from a coding viewpoint, but if you know ahead of time a column is going to be a date, then format it as you insert the data into the table.

    private void processExcel(string filename)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
    
        var missing = System.Reflection.Missing.Value;
    
        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    
        Excel.Range xlRange = xlWorkSheet.UsedRange;
        Array myValues = (Array)xlRange.Cells.Value2;
    
        int vertical = myValues.GetLength(0);
        int horizontal = myValues.GetLength(1);
    
        DataTable dt = new DataTable();
    
        // must start with index = 1
        // get header information
        for (int i = 1; i <= horizontal; i++)
        {
            dt.Columns.Add(new DataColumn(myValues.GetValue(1,i).ToString()));
        }
    
        // Get the row information
        for (int a = 2; a <= vertical; a++)
        {
            object[] poop = new object[horizontal];
            for (int b = 1; b <= horizontal; b++)
            {
                poop[b - 1] = myValues.GetValue(a, b);
            }
            DataRow row = dt.NewRow();
            row.ItemArray = poop;
            dt.Rows.Add(row);
        }
    
        // assign table to default data grid view
        dataGridView1.DataSource = dt;
    
        xlWorkBook.Close(true, missing, missing);
        xlApp.Quit();
    
        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    }
    
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }
    
    0 讨论(0)
  • 2021-01-29 11:48

    Those codes above does not work. That code works for me (.NET Framework 4.7.1)

    private void processExcel(string filename)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
    
        var missing = System.Reflection.Missing.Value;
    
        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, Excel.XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    
        Excel.Range xlRange = xlWorkSheet.UsedRange;
        Array myValues = (Array)xlRange.Cells.Value2;
    
        int vertical = myValues.GetLength(0);
        int horizontal = myValues.GetLength(1);
    
        DataTable dt = new DataTable();
    
        // must start with index = 1
        // get header information
        try
        {
            for (int i = 1; i <= horizontal; i++)
            {
                dt.Columns.Add(new DataColumn(Convert.ToString(myValues.GetValue(1, i))));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    
    
        // Get the row information
        for (int a = 2; a <= vertical; a++)
        {
            object[] rows = new object[horizontal];
            for (int b = 1; b <= horizontal; b++)
            {
                rows[b - 1] = myValues.GetValue(a, b);
            }
            DataRow row = dt.NewRow();
            row.ItemArray = rows;
            dt.Rows.Add(row);
        }
    
        // assign table to default data grid view
        dataGridView1.DataSource = dt;
    
        xlWorkBook.Close(true, missing, missing);
        xlApp.Quit();
    
        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    }
    
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }
    
    0 讨论(0)
  • 2021-01-29 11:59
        using Excel = Microsoft.Office.Interop.Excel;
    

    You'll obviously need to add the reference to your project, and then it's plain simple :)

        private void ProcessExcel(string filepath)
        {
    
                Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass();
    
                Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    
                Excel.Sheets sheets = theWorkbook.Worksheets;
    
                Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
    
                Excel.Range range = worksheet.UsedRange;
    
                System.Array myvalues = (System.Array)range.Cells.Value2;
    
                int vertical = myvalues.GetLength(0);
                int horizontal = myvalues.GetLength(1);
    
    
    
                string[] headers = new string[horizontal];
                string[] data = new string[horizontal];
    
    
                DataTable ResultsHeader = New DataTable();
                DataSet ds = New DataSet();
    
    
                for (int x = 1; x <= vertical; x++)
                {
                        Utils.inicializarArrays(datos);
                        for (int y = 1; y <= horizontal; y++)
                        {
                            if (x == 1)
                            {
                                headers[y - 1] = myvalues.GetValue(x, y).ToString();
                            }
                            else
                            {
                                string auxdata = "";
                                if (myvalues.GetValue(x, y) != null)
                                    auxdata = myvalues.GetValue(x, y).ToString();
                                data[y - 1] = auxdata;
                            }
    
                        }
                        if(x == 1) //headers
                        {
                                for(int w = 0; w < horizontal; w++)
                                {
                                        ResultsHeader.Columns.Add(New DataColumn(headers[w], GetType(string)));
                                }
                                ds.Tables.Add(ResultsHeader);
                        }
                        else
                        {
                                DataRow dataRow = ds.Tables[0].NewRow();
                                for(int w = 0; w < horizontal; w++)
                                {
                                        dataRow(headers[w]) = data[w]
                                }
                                ds.Tables[0].Rows.Add(dataRow);
                        }
                }
                DataView myDataView = new DataView();
                myDataView.Table = ds.Tables[0];
                MydataGrid.CurrentPageIndex = 0;
                MydataGrid.DataSource = myDataView;
                MydataGrid.DataBind();
        }
    
    0 讨论(0)
提交回复
热议问题