我正在尝试读取Excel文档中的字段,并使用Binding List将值存储到相应的变量中,并将其导出到Sql Server 2008数据库
以下是我在网上找到的代码
public void csv() {
try
{
MyApp = new Excel.Application();
MyApp.Visible = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.ShowDialog();
MyBook = MyApp.Workbooks.Open(ofd.FileName);
MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
var lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
BindingList<ExportExcel> EmpList = new BindingList<ExportExcel>();
for (int index = 2; index <= lastRow; index++)
{
System.Array MyValues = (System.Array)MySheet.get_Range("A" + index.ToString(), "G" + index.ToString()).Cells.Value;
EmpList.Add(new ExportExcel
{
PersonName = MyValues.GetValue(1, 1).ToString(),
Product = MyValues.GetValue(1, 2).ToString(),
StartDate = Convert.ToDateTime(MyValues.GetValue(1, 3).ToString()),
ExpiresOn = Convert.ToDateTime(MyValues.GetValue(1, 4).ToString()),
DaysIssued = MyValues.GetValue(1, 5).ToString(),
TrialsIssued = MyValues.GetValue(1, 6).ToString(),
Contact = MyValues.GetValue(1, 7).ToString()
});
query = "EXEC dbo.proc_ImportExcel'" + PersonName + "', '" + Product + "','" + StartDate + "','" + DaysIssued + "','" + ExpiresOn + "','" + TrialsIssued + "','" + Contact + "'";
}
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我在行 PersonName = MyValues.GetValue(1,1).ToString(),中获取了正确的值,并且这些值未存储在变量personName中,而值显示在line MyValues.GetValue(1,1).ToString(),我得到的错误对象引用没有设置为对象的实例。
任何人都可以帮我解决这个问题。
由于