在錯誤信息當範圍恰好由一個c組成時,就會發生原始帖子因爲結果值的類型是變體,實際上可以是數組,雙精度型,字符串型,日期型和空值。
一種解決方案可以是檢查細胞數量,並在僅有一個細胞的情況下采取不同的行爲。
我的解決方案創建一個單元格數組。即使一個或多個單元格爲空,這可能會導致空對象。 (當範圍內的所有細胞都是空的,Range.Cells.Value爲空)。
System.Array cellArray = range.Cells.Cast<Excel.Range>().ToArray<Excel.Range>();
如果你喜歡在列表陣列(像我這樣做),你可以使用此代碼:
List<Excel.Range> listOfCells = range.Cells.Cast<Excel.Range>().ToList<Excel.Range>();
範圍可以是一維或二維。
最後,如果你確實需要一個字符串數組,那就是:
string[] strArray = range.Cells.Cast<Excel.Range>().Select(Selector).ToArray<string>();
其中選擇功能看起來是這樣的:
public string Selector(Excel.Range cell)
{
if (cell.Value2 == null)
return "";
if (cell.Value2.GetType().ToString() == "System.Double")
return ((double)cell.Value2).ToString();
else if (cell.Value2.GetType().ToString() == "System.String")
return ((string)cell.Value2);
else if (cell.Value2.GetType().ToString() == "System.Boolean")
return ((bool)cell.Value2).ToString();
else
return "unknown";
}
中,我有我不」的情況「未知」請記住Value2可以返回的所有數據類型。如果您發現任何其他類型,請改進此功能。
至少應該像'Range.Cells.Value'這樣大寫。但是沒有足夠的有關您的問題的信息。請澄清一下。 –
現在我更新了代碼。 – user3217843
可以請你提供我的鏈接。 – user3217843