Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't test the data type of the entire column because Excel does not restrict the data types of all the cells in the column to be the same. You would have to test the data type held in individual cells.</p> <p>As long as the cell is not empty, you can test for the data type held by the cell by calling the <code>Object.GetType()</code> method on the value held by the cell:</p> <pre><code>// Using C# 4.0 Type type = worksheet.Cells[1,1].Value.GetType(); </code></pre> <p>Using C# 3.0 would be a little more cumbersome:</p> <pre><code>// Using C# 3.0 Type type = (worksheet.Cells[1, 1] as Excel.Range).get_Value(Type.Missing).GetType(); </code></pre> <p>If the cell could be empty, however, you'll have to test for that because the <code>Range.Value</code> returned by an empty cell is <code>null</code>, and you can't call <code>Object.GetType()</code> on <code>null</code>. Therefore, you have to test for <code>null</code> explicitly:</p> <pre><code>// Testing Cell Data Type via C# 4.0 object value = worksheet.Cells[1,1].Value; string typeName; if (value == null) { typeName = "null"; } else { typeName = value.GetType().ToString(); } MessageBox.Show("The value held by the cell is a '" + typeName + "'"); </code></pre> <p>If using C# 3.0, the code is similar:</p> <pre><code>// Testing Cell Data Type via C# 3.0 object value = (worksheet.Cells[1, 1] as Excel.Range).get_Value(Type.Missing); string typeName; if (value == null) { typeName = "null"; } else { typeName = value.GetType().ToString(); } MessageBox.Show("The value held by the cell is a '" + typeName + "'"); </code></pre> <p>Hope this helps...</p> <p>-- Mike</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload