c#-4.0 – 如何使用C#.net中的EXCEL interop api读取空单元格值?

前端之家收集整理的这篇文章主要介绍了c#-4.0 – 如何使用C#.net中的EXCEL interop api读取空单元格值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我尝试读取空的EXCEL单元格,则会收到System.com_object错误.我的代码是:
  1. public static List<OrderPC> getFilters(string fileCheckout)
  2. {
  3. List<OrderPC> orderPCs = new List<OrderPC>();
  4. XLDoc sldoc = new XLDoc();
  5.  
  6. string localPath = @"C:\Temp\PCs.xlsx";
  7.  
  8. Microsoft.Office.Interop.Excel.Application oXL=null;
  9. Microsoft.Office.Interop.Excel.Workbook mWorkBook=null;
  10. Microsoft.Office.Interop.Excel.Worksheet mWSheet1=null;
  11. Microsoft.Office.Interop.Excel.Range xlRange=null;
  12. try
  13. {
  14. oXL = new Microsoft.Office.Interop.Excel.Application();
  15.  
  16. mWorkBook = oXL.Workbooks.Open(localPath);
  17.  
  18. mWSheet1 = mWorkBook.Sheets[1];
  19.  
  20. xlRange = mWSheet1.UsedRange;
  21.  
  22. foreach (Microsoft.Office.Interop.Excel.Hyperlink hl in xlRange.Hyperlinks)
  23. {
  24.  
  25. int y = hl.Range.Column;
  26.  
  27. int z = hl.Range.Row;
  28.  
  29. string vFilter = mWSheet1.Cells[z,y + 1].Value2.Trim();
  30.  
  31. if (vFilter.CompareTo("Weekly") == 0)
  32. {
  33. String baseUri = "http://xxx.yyy.net?";
  34. int followUpIndex = baseUri.Length;
  35. OrderPC orderPc = new OrderPC();
  36. orderPc.ProductClass = hl.TextToDisplay.Trim();
  37. orderPc.HyperLink = hl.Address.Trim().Substring(followUpIndex);
  38. orderPc.SpecType = mWSheet1.Cells[z,y - 1].Value2.Trim();
  39. if (mWSheet1.Rows[z].Cells[y + 3] != null || mWSheet1.Rows[z].Cells[y + 3].Value2 != string.Empty)
  40. {
  41. orderPc.ManufactureDate = mWSheet1.Cells[z,y + 3].Value2.ToString(); //Here is the error**
  42. }
  43. //Console.WriteLine(orderPc.ProductClass+"----"+orderPc.HyperLink);
  44.  
  45. orderPCs.Add(orderPc);
  46. }
  47. }
  48. }
  49. catch (Exception ex)
  50. {
  51. }
  52. finally
  53. {
  54. GC.Collect();
  55. GC.WaitForPendingFinalizers();
  56.  
  57. Marshal.FinalReleaseComObject(xlRange);
  58. Marshal.FinalReleaseComObject(mWSheet1);
  59.  
  60. mWorkBook.Close(Type.Missing,Type.Missing,Type.Missing);
  61. Marshal.FinalReleaseComObject(mWorkBook);
  62.  
  63. oXL.Quit();
  64. Marshal.FinalReleaseComObject(oXL);
  65. }
  66. return orderPCs;
  67. }

这个excel文件有10列,我想我正在读一个有效的单元格.错误是**“

{Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法对空引用执行运行时绑定
在CallSite.Target(Closure,CallSite,Object)
在System.Dynamic.UpdateDelegates.UpdateAndExecute1 [T0,TRet](CallSite站点,T0 arg0)

“**我的COM没有任何线索.非常感谢帮助.

解决方法

添加另一张支票
  1. if (mWSheet1.Cells[z,y + 3].Value2 != null)

或使用以下代码转换为字符串,因为如果Value2为null,它将不会失败

  1. orderPc.ManufactureDate = Convert.ToString(mWSheet1.Cells[z,y + 3].Value2);

猜你在找的C#相关文章