所以,我试图制作一个Excel文档解析器,一切顺利,直到它在Excel中击中空单元格。然后它抛出异常* System.Core.dll中出现“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”“
namespace ExcelParser {
class Program
{
static void Main(string[] args)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
string _sourceFile = "F:\\Bullshit\\book1.xlsm";
excelApp.Workbooks.Open(_sourceFile);
int row = 1;
Excel.Worksheet currentSheet = (Excel.Worksheet)excelApp.Workbooks[1].Worksheets[1];
Console.WriteLine("Initializing");
while (currentSheet.get_Range("A" + row).Value2 != null)
{
List<string> tempList = new List<string>();
for (char column = 'A'; column < 'J'; column++)
{
Console.Write(column + row.ToString());
Excel.Range cell = currentSheet.get_Range(column + row.ToString());
Console.WriteLine(cell.Value2.ToString() != "" ? cell.Value2.ToString() : "null!"); // the problem line
}
row++;
}
Console.ReadKey();
}
}
}
答案 0 :(得分:0)
如果没有对象,则无法强制转换对象的ToString方法。它将返回null,但null
与""
不同,请尝试使用此行:
Console.WriteLine(("" + cell.Value2).ToString() != "" ? cell.Value2.ToString() : "null!");
答案 1 :(得分:0)
摆脱异常的快速而肮脏的方法就是
try
{
Console.WriteLine(cell.Value2.ToString() != "" ? cell.Value2.ToString(): "null!");
}
catch(exception e)
{
Console.WriteLine(e.Argument);
}
答案 2 :(得分:0)
对于空单元格,我猜%// read FIRST block
fid = fileopen(fileName);
M = textscan(fid, readFormat, nLines,'Delimiter',' ');
lastPosition = ftell(fid) ;
fclose(fid)
%// do some stuff
%// then read another block:
fid = fileopen(fileName);
fseek( fid , 'bof' , lastPosition ) ;
M = textscan(fid, readFormat, nLines,'Delimiter',' ');
lastPosition = ftell(fid) ;
fclose(fid)
%// and so on ...
为空。在这种情况下,您无法在其上调用.ToString()。
然而,您可以检查它:
cell.Value2