Importing Excel into DataGridView

坚强是说给别人听的谎言 提交于 2021-01-29 00:03:32

问题


I'm making a program where two databases are merged together.... I can import an excel spreadsheet into a DataGridView with this code:

     string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls;Extended Properties=""Excel 8.0;HDR=YES;IMEX=1""";

                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

                DbDataAdapter adapter = factory.CreateDataAdapter();

                DbCommand selectCommand = factory.CreateCommand();
                selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";

                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;

                selectCommand.Connection = connection;

                adapter.SelectCommand = selectCommand;

                data = new DataSet();

                adapter.Fill(data);

                dataGridView1.DataSource = data.Tables[0].DefaultView;

The problem I'm having is that I'm trying to find a way to change the source file to path that is returned by a dialog box. I have a string file that contains the file path. How do I incorporate this into the connection string?

Or maybe there is an altogether better way to do this?

Thanks!

Luke


回答1:


Use the OleDbConnectionStringBuilder class to modify your connection string.

string fileName = "your path to the excel.xls"; // From the dialog box.

OleDbConnectionStringBuilder connStringBuilder =
    new OleDbConnectionStringBuilder();

connStringBuilder.DataSource = fileName;  // Set path to excel file
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=YES;IMEX1");        

...

// Get the connection string from the builder.
connection.ConnectionString = connStringBuilder.ConnectionString; 



回答2:


You just need Microsoft.Office.Interop.Excel and combine it with datatable and dataset.

    Excel.Workbook ExWorkbook;
    Excel.Worksheet ExWorksheet;
    Excel.Range ExRange;
    Excel.Application ExObj = new Excel.Application();

    DataTable dt = new DataTable("dataTable");
    DataSet dsSource = new DataSet("dataSet");
    dt.Reset();

    openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
    DialogResult result = openFileDialog1.ShowDialog();

    if (result == DialogResult.OK) // Test result.
    {
        ExWorkbook = ExObj.Workbooks.Open(openFileDialog1.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
        ExWorksheet = (Excel.Worksheet)ExWorkbook.Sheets.get_Item(1);
        ExRange = ExWorksheet.UsedRange;

        for (int Cnum = 1; Cnum <= ExRange.Columns.Count; Cnum++)
        {
            dt.Columns.Add(new DataColumn((ExRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
        }
        dt.AcceptChanges();

        string[] columnNames = new String[dt.Columns.Count];
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            columnNames[0] = dt.Columns[i].ColumnName;
        }

        for (int Rnum = 2; Rnum <= ExRange.Rows.Count; Rnum++)
        {
            DataRow dr = dt.NewRow();
            for (int Cnum = 1; Cnum <= ExRange.Columns.Count; Cnum++)
            {
                if ((ExRange.Cells[Rnum, Cnum] as Excel.Range).Value2 != null)
                {
                    dr[Cnum - 1] = (ExRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
                }
            }
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }
        ExWorkbook.Close(true, Missing.Value, Missing.Value);
        ExObj.Quit();

        dataGridView1.DataSource = dt;  


来源:https://stackoverflow.com/questions/11349370/importing-excel-into-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!