2014-02-06 16 views
0

我想使用C#在Excel中獲取非連續的多區域範圍的值。我已經看到another SO question,說我可以做這樣的事情:Excel:來自多個區域的範圍的值

obj[,] data = sheet.get_Range("B4:K4,B5:K5").get_Value(); 

然而,當我檢查的結果我看到,我只能從第一區中的數據:"B4:K4"

進一步的測試,我發現,如果我要求以下列方式中的數據:

obj[,] data = sheet.get_Range("B4:K4","B5:K5").get_Value(); 

我得到的數據,這兩個領域...

所以,我的問題是,有沒有以編程方式組合區域地址(例如"B4:K4,B5:K5")以便獲取它們引用的所有數據的方法?

感謝

+0

難道這是它會工作時,你使用分號而不是逗號?有時候,excel對這些事情很有趣......這只是一個預感/猜測! – Floris

+0

@pnuts:我忘了說區域可以不連續。上面編輯。 –

+0

http://msdn.microsoft.com/en-us/library/office/aa213609%28v=office.11​​%29.aspx也許? – pnuts

回答

1

我想出瞭解決的辦法是不優雅,我希望的,但它仍然技巧:

public List<List<object>> 
GetNonContiguousRowValue(Excel.Worksheet ws, string noncontiguous_address) 
{ 
    var addresses = noncontiguous_address.Split(','); // e.g. "A1:D1,A4:D4" 
    var row_data = new List<List<object>>(); 

    // Get the value of one row at a time: 
    foreach (var addr in addresses) 
    { 
     object[,] arr = ws.get_Range(addr).Value; 
     List<object> row = arr.Cast<object>) 
           .Take(arr.GetLength(dimension:1)) 
           .ToList<object>(); 
     row_data.Add(row); 
    } 
    return row_data; 
} 

希望這可以幫助其他人...

0

如果您試圖從隱藏行的範圍表中獲取數據,另一種方法是獲取可見單元格,並將它們複製到新的工作表中。當粘貼時,它們將形成一個連續的區域,並且可以檢索正常的對象[,]數組。

public object[,] GetNonContiguousVisibleRowsData(Excel.Worksheet sheet, string noncontiguous_address) 
{ 
    // Add a new worksheet 
    Excel.Workbook book = (Excel.Workbook)sheet.Parent; 
    Excel.Sheets sheets = book.Sheets; 
    Excel.Worksheet tempSheet = (Excel.Worksheet)sheets.Add(); 
    Excel.Range cellA1 = tempSheet.get_Range("A1"); 

    // Get only the visible cells 
    Excel.Range nonContiguousRange = sheet.get_Range(noncontiguous_address); 
    Excel.Range visibleSourceRange = nonContiguousRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible); 

    // Copying the visible cells will result in a contiguous range in tempSheet 
    visibleSourceRange.Copy(cellA1); 

    // Get the contiguous range and copy the cell value. 
    Excel.Range contiguousRange = tempSheet.UsedRange; 
    object[,] data = (object[,])contiguousRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault); 

    // Release all COM objects from temp sheet, e.g.: 
    // System.Runtime.InteropServices.Marshal.ReleaseComObject(contiguousRange); 
    // contiguousRange = null; 

    tempSheet.Delete(); 

    // release all other COM objects 

    return data; 
} 
0

另一種方法是將非連續區域組合到一個命名區域中,並在C#代碼中引用該命名區域。這裏是一個辦法做到這一點(這個公式分配到Excel名稱管理器中的命名範圍):

=CHOOSE({1;2;3},Sheet1!$A$1,Sheet2!$A$3,Sheet3!$A$5) 

的缺點用這種方法是,每個區只能是1排高。