2015-06-03 38 views
0

我是新來的編碼,我試圖將每個客戶的信息(Id num,name,birthday)都存入自己的數組中。到目前爲止,我能夠讀取Excel中的數據我只是不知道如何商店它在一個數組,我不知道如何轉換「valueArray」從對象到字符串數組將客戶數據從excel讀取到數組中

static void Main(string[] args) 
{ 
    // Reference to Excel Application. 
    Excel.Application xlApp = new Excel.Application(); 

    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath("excelpractice1.xlsx")); 

    // Get the first worksheet. 
    Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1); 

    // Get the range of cells which has data. 
    Excel.Range xlRange = xlWorksheet.UsedRange; 

    // Get an object array of all of the cells in the worksheet with their values. 
    object[,] valueArray = (object[,])xlRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault); 

    // iterate through each cell and display the contents. 
    for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row) 
    { 
     Console.WriteLine(valueArray[row, row].ToString()); 
    } 

    // Close the Workbook. 
    xlWorkbook.Close(false); 

    // Relase COM Object by decrementing the reference count. 
    Marshal.ReleaseComObject(xlWorkbook); 

    // Close Excel application. 
    xlApp.Quit(); 

    // Release COM object. 
    Marshal.FinalReleaseComObject(xlApp); 

    Console.ReadLine(); 
} 

回答

0

事情是這樣的:

String[,] arr = new String[xlWorksheet.UsedRange.Rows.Count,xlWorksheet.UsedRange.Columns.Count]; 
for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row) 
{ 
     for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col) 
     { 
     arr[row,col] = valueArray[row, col].ToString(); 
     } 
} 

您還可以使用Array.Copyhere

Btw。不知道,但我認爲你應該也需要發佈xlRange

相關問題