Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c# - Worksheet get_Range throws exception

I'm using C# to manipulate an Excel worksheet. The following two pieces of code should work the same, but one works and the other throws an exception. I wonder why.

This works:

oRange = (Excel.Range)oSheet.get_Range("A1","F1");
oRange.EntireColumn.AutoFit();

This throws an exception:

oRange = (Excel.Range)oSheet.get_Range(oSheet.Cells[1, 1],oSheet.Cells[4,4]);
oRange.EntireColumn.AutoFit();

Exception:

RuntimeBinderException occurred. "object" does not contain a definition for 'get_Range'

The oSheet is instantiated as follows:

Excel.Worksheet oSheet = new Excel.Worksheet();

Am I supposed to instantiate both differently?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like the exception is thrown from the oSheet.Cells[1, 1] and oSheet.Cells[4, 4] used as arguments to get_range.

Applying the following, no exception will be thrown:

Excel.Range c1 = oSheet.Cells[1, 1];
Excel.Range c2 = oSheet.Cells[4, 4];
oRange = (Excel.Range)oSheet.get_Range(c1, c2);
oRange.EntireColumn.AutoFit();

So, it might be related to the oSheet.get_Range functionality. It receives an object as an argument, therefore it might try to invoke a get_Range method on the arguments to receive the internal cell, and the up-cast from Range to object done by the compiler might hide the method call.

If you need the cells definition by row/column - try using the above approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...