0

我正在尝试在不进行硬编码样式的情况下将 Excel 读取到数据网格视图。我在尝试执行此操作时遇到了错误。谁能帮我解决这个问题?

Excel.Workbook workbook;
        Excel.Worksheet NwSheet;
        Excel.Range ShtRange;
        Microsoft.Office.Interop.Excel.Application ExcelObj = null;
        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)
        {
            //Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
            //   filedlgExcel.FileName, 0, true, 5,
            //    "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
            //    0, true);
           workbook = ExcelObj.Workbooks.Open(filedlgExcel.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);
            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 Day")
                {
                    es.day = day;
                    es.startTime = split[0];
                    es.endTime = split[0];
                    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;
        }
            }
        }

他们在这部分向我显示了一个错误“对象引用未设置为对象的实例”。

workbook = ExcelObj.Workbooks.Open(filedlgExcel.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);

任何帮助将不胜感激。

4

2 回答 2

1

您在开始时将 ExcelObj 设置为 null ,然后从不初始化它

Microsoft.Office.Interop.Excel.Application ExcelObj = null;

试着做= new Microsoft.Office.Interop.Excel.Application();

于 2012-07-17T08:06:28.707 回答
1

或者,您可以使用OleDb提供程序来读取 Excel 工作表。

string cnStr=@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties=" + "\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
DataTable dt=new DataTable();
string sql="Select * From [Sheet1$]";
using(OleDbConnection cn=new OleDbConnection(cnstr))
{
  using(OleDbDataAdapter adapter=new OleDbDataAdapter(sql,cn))
   {
     adapter.Fill(dt);
   }
}

OleDb 是 ADO.NET 的提供者 API(.net 框架的数据库集成 API),它公开来自不同数据源的数据,包括 Microsoft Access 数据库或 Microsoft Excel 电子表格等等。

查看 MSDN 文章/教程的链接:

  1. 如何使用 ADO.NET 通过 Visual Basic .NET 检索和修改 Excel 工作簿中的记录
  2. 如何使用 Visual C# 2005 或 Visual C# .NET 将数据传输到 Excel 工作簿
于 2012-07-17T08:08:49.670 回答