The following table summarizes the ways you can get or set data in cells using the properties of the cell.
Data Description | Cell Property |
---|---|
As a string with formatting (for example "$1,234.56") |
|
As a string without formatting (for example "1234.45") |
There is no limitation on the data types of values that can be stored in cells. Cell values are assigned and retrieved using the generic Object data type. Primitive data types (for example, bool, int, double, etc.) are assigned and retrieved using boxed primitives.
The C# and Visual Basic .NET languages automatically box primitives (that is, convert primitive to object) for you as illustrated in this code.
Code
C# | Copy Code |
---|---|
spread.Sheets[0].Cells[0, 3].Value = 123;
spread.Sheets[0].SetValue(0, 6, "abc");
|
VB | Copy Code |
---|---|
spread.Sheets(0).Cells(0, 3).Value = 123
spread.Sheets(0).SetValue(0, 6, "abc")
|
But you must manually unbox primitives (that is, convert object to primitive) by using a cast:
Code
C# | Copy Code |
---|---|
int i = (int)spread.Sheets[0].Cells[0, 3].Value; string s = (string)spread.Sheets[0].GetValue(0, 6); |
VB | Copy Code |
---|---|
Dim i As Integer = CInt(spread.Sheets(0).Cells(0, 3).Value) Dim s As String = CStr(spread.Sheets(0).GetValue(0, 6)) |
Note: Empty cells return a null value (Nothing in VB) which causes the cast to fail. If there is a possibility that a cell is empty or contains a value of unknown data type then your code should check the data type prior to performing the cast or should provide an exception handler to catch the exception thrown by the failed cast.