0

在此处输入图像描述

嗨,大家好!我遇到的一个问题是我很难将这个 Excel 文件读取到数据网格视图中,如上图所示。任何帮助将不胜感激。谢谢。

这些是我读取 Excel 文件的代码,但有一个错误,我很难对其进行故障排除。

private void btnSearch_Click(object sender, EventArgs e)
    {
        Excel.Workbook workbook;
        Excel.Worksheet NwSheet;
        Excel.Range ShtRange;
        Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
        OpenFileDialog filedlgExcel = new OpenFileDialog();
        filedlgExcel.Title = "Select file";
        filedlgExcel.InitialDirectory = @"c:\";
        filedlgExcel.FileName = txtFileName.Text;
        filedlgExcel.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
        filedlgExcel.FilterIndex = 1;
        filedlgExcel.RestoreDirectory = true;
        if (filedlgExcel.ShowDialog() == DialogResult.OK)
        {
           workbook = ExcelObj.Workbooks.Open(filedlgExcel.FileName);
            NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
        ShtRange = NwSheet.UsedRange; //gives the used cells in sheet
        //Reading Excel file.
        //Creating dataTable to read the containt of the Sheet in File.

        //Set header name
        for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
        {
            dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));
        }
        dt.AcceptChanges();
        //store coumn names to array
        string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();

        //populate fields
        for (int Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
        {
            DataRow dr = dt.NewRow();
            for (int Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
            {
                dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
            }
            dt.Rows.Add(dr);
            dt.AcceptChanges();
        }
        workbook.Close(true, Missing.Value, Missing.Value);
        ExcelObj.Quit();

        foreach (DataRow dr in dt.Rows)
        {
            string strEmployee = dr["Employee Name"].ToString();
            obj1 = new List<employeeschedule>();
            for (int i = 1; i < dt.Columns.Count; i++)
            {
                string period = dr[i].ToString();
                string[] split = period.Split('–');
                employeeschedule es = new employeeschedule();
                string day = columnNames[i];
                if (split[0] == "REST")
                {
                    es.day = day;
                    es.startTime = "0000";
                    es.endTime = "0000";
                    es.restDay = "Yes";
                }
                if (split[0] == "OFF")
                {
                    es.day = day;
                    es.startTime = "0000";
                    es.endTime = "0000";
                    es.restDay = "Yes";
                }
                else
                {
                    es.day = day;
                    es.startTime = split[0];
                    es.endTime = split[1];
                    es.restDay = "No";
                }
                obj1.Add(es);
            }

            dict.Add(strEmployee, obj1);
            dgvEmployeeShift.DataSource = dt;
        }
            }
        }

错误落在这部分:

 dt.Columns.Add(new DataColumn((ShtRange.Cells[1, Cnum] as Excel.Range).Value2.ToString()));

它指出“无法对空引用执行运行时绑定”。

4

2 回答 2

1

我喜欢在自动化 Excel 时使用 Interop,但出于您的要求,为什么不使用OleDb呢?它比使用互操作快得多?

久经考验

    private void btnSearch_Click(object sender, EventArgs e)
    {
        System.Data.OleDb.OleDbConnection MyCon ;
        System.Data.DataSet DtSet ;
        System.Data.OleDb.OleDbDataAdapter MyCommand ;

        //~~> Replace this with relevant file path
        MyCon = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Sample.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\"");

        //~~> Replace this with the relevant sheet name
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyCon);

        MyCommand.TableMappings.Add("Table", "MyTable");
        DtSet = new System.Data.DataSet();

        //~~> Fill Dataset
        MyCommand.Fill(DtSet);

        //~~> Set Source
        dataGridView1.DataSource = DtSet.Tables[0];
        MyCon.Close();
    }
于 2012-08-08T07:04:26.760 回答
0

这对我有用............浏览您的本地文件夹,选择excel,在网格视图中显示。我建议使用 oledb

private void OpenFile_Click(object sender, EventArgs e) { OpenFileDialog openfiledialog1 = new OpenFileDialog(); if (openfiledialog1.ShowDialog()==System.Windows.Forms.DialogResult.OK) { this.textBox_path.Text = openfiledialog1.FileName;

        }


    }

    private void LoadExcel_Click(object sender, EventArgs e)
    {
        //string pathConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+textBox_path.Text+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
        string pathConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_path.Text + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
        OleDbConnection conn = new OleDbConnection(pathConn);

        conn.Open();
        OleDbDataAdapter mydataadapter = new OleDbDataAdapter("Select * from ["+textBox_sheet.Text+"$]", conn);
        DataTable dt = new DataTable();

        mydataadapter.Fill(dt);
        dataGridView1.DataSource = dt;

        conn.Close();
     }
于 2014-03-03T09:43:52.220 回答