嗨我不斷從下面的代碼中獲取此錯誤,想知道是否有人可以幫助。空引用Excel文檔C#
error processing excel file: cannot perform runtime binding on a null reference
代碼:
private void Import_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
Microsoft.Office.Interop.Excel.Application vExcelObj = new Microsoft.Office.Interop.Excel.Application();
try
{
Microsoft.Office.Interop.Excel.Workbook theWorkbook = vExcelObj.Workbooks.Open(filename, Type.Missing, true);
Microsoft.Office.Interop.Excel.Worksheet sheet = theWorkbook.Worksheets[1];
string vFirstName = "temp";
string vLastName = "temp";
int vIndex = 1;
while (vFirstName != "")
{
// Change the letters of the appropriate columns here!
// In my example, 'A' is first name, 'B' last name
vFirstName = sheet.get_Range("A" + vIndex.ToString()).Value.ToString(); // if i take out the exception handling the error is on this line
vLastName = sheet.get_Range("B" + vIndex.ToString()).Value.ToString();
this.SaveNewCustomer(vFirstName, vLastName);
vIndex++;
}
}
catch (Exception ex)
{
MessageBox.Show("Error processing excel file : " + ex.Message);
}
finally
{
vExcelObj.Quit();
}
}
}
private void SaveNewCustomer(string firstName, string lastName)
{
string uri = "http://localhost:8002/Service/Customer";
StringBuilder sb = new StringBuilder();
sb.Append("<Customers>");
sb.AppendLine("<FirstName>" + firstName + "</FirstName>");
sb.AppendLine("<LastName>" + lastName + "</LastName>");
sb.AppendLine("</Customers>");
string NewStudent = sb.ToString();
byte[] arr = Encoding.UTF8.GetBytes(NewStudent);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/xml";
req.ContentLength = arr.Length;
Stream reqStrm = req.GetRequestStream();
reqStrm.Write(arr, 0, arr.Length);
reqStrm.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
reqStrm.Close();
resp.Close();
}
}
的代碼只是需要一個excel文件,並改掉將數據發送到我的web服務。
所以我嘗試使用下面的方法,但它凍結了應用程序:S沒有錯誤只是掛起。 編輯嘗試:
while (vFirstName != "")
{
var columnACell = sheet.get_Range("A" + vIndex.ToString());
var columnBCell = sheet.get_Range("B" + vIndex.ToString());
var columnACellValue = columnACell.Value;
var columnBCellValue = columnBCell.Value;
if (columnACellValue != null && columnBCellValue != null)
{
vFirstName = columnACellValue.ToString();
vLastName = columnBCellValue.ToString();
this.SaveNewStaff(vFirstName, vLastName); //, vPassword
vIndex++;
}
}
}
哪一行引發異常? – Steve 2012-07-24 20:12:29
'vFirstName = sheet.get_Range(「A」+ vIndex.ToString())。Value.ToString();' – 2012-07-24 20:15:38
我想這個值返回null,然後調用ToString()失敗。檢查在對象var中獲取Value並測試它是否爲null。 – Steve 2012-07-24 20:18:23