简体   繁体   中英

c# code to get the data from .xlsx file and store it into an int[]

i am try to get data from excel file and save it in int [] array=new int[9]; want to do this using for loop , in order to get value from file "one row at a time" . i done with reading data fro file but couldont store it into int [] through iteration.

    static void Main()
    {
        string i="B1410";
        string j="J1410";
        Excel.Application xlApp = new Excel.Application();
   Excel.Workbook xlWorkbook = 

    xlApp.Workbooks.Open(@"E:\Normalized_sheet1.xlsx");
        string currentsheet = "Sheet1";
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[currentsheet];
        Excel.Range xlRange = xlWorksheet.get_Range(i, j.ToString());
        Object[,] valueArray = 

     (Object[,])xlRange.get_Value(Excel.XlRangeValueDataType.
    xlRangeValueDefault);
      int[] array = new int[9];

       array =  Convert.ToInt32((Object[,])xlRange.get_Value
                 (Excel.XlRangeValueDataType.xlRangeV    
                  alueDefault.ToString()));   //Error
        //want to enter values row wise one by one through loop


       //close the workbook 

        xlWorkbook.Close(false);

        // Release Com object by decrementing the reference count

        xlApp.Quit();
        Console.ReadLine();

   }

Your array is only scoped to the for loop.

for (int k = 1; k < 500; k++)
{
    int[] array = new int[9];
}

Declare it outside.

int[] array = new int[9];
for (int k = 1; k < 500; k++)
{
    // ...
}

Your array is only 9 elements long, but k can by up to 499 . You can't insert one element into this array per iteration of the for loop as you'll get in IndexOutOfBoundsException thrown.

array probably needs to be the same size as the max value of k , ie 499.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM