ハード コーディング スタイルを使用せずに、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);
どんな助けでも大歓迎です。