Possible Duplicate:
Read data from Excel files
I'm having some trouble reading from an Excel spreadsheet in C#. I have this code which I read every cell from A to X.
int i = 1;
int number;
System.Array myvalues; string[] strArray;
Microsoft.Office.Interop.Excel.Range range =
worksheet.get_Range("A" + i.ToString(), "X" + i.ToString());
while(range.Count!=0)
{
i++;
range = worksheet.get_Range("A" + i.ToString(), "X" + i.ToString());
myvalues = (System.Array)range.Cells.Value;
strArray = ConvertToStringArray(myvalues);
number = Convert.ToInt32(strArray[0]);
}
My question is: How could i read next 4 * "number" rows in excel based on "number" value ?
For example:
A B C D E F G H I J
a a a a a 1 a a a a
F's cell value is 1 so I would like to read ( G H I J) If F's cell value is 2 the I would like to read ( G H I J K L M N)
A B C D E F G H I J K L M N
a a a a a 2 a a a a a a a a
F's cell value 3 :
A B C D E F G H I J K L M N O P Q R
a a a a a 3 a a a a a a a a a a a a
.
if (!number_add_file.Equals("") )
{
addcmpy();
Microsoft.Office.Interop.Excel.Range range_add = worksheet.get_Range("X"+i.ToString() , "AA" + i.ToString());
while(range_add.Count != 0){
if (Int32.Parse(number_add_file) == 2)
{
range_add = worksheet.get_Range("X"+i.ToString() , "AE"i.ToString() );
}
else if (Int32.Parse(number_add_file) == 3)
{
range_add = worksheet.get_Range("X"i.ToString() , "AI"i.ToString());
}
else if (Int32.Parse(number_add_file) == 4)
{
range_add = worksheet.get_Range("X"i.ToString() , "AM"i.ToString());
}
else if (Int32.Parse(number_add_file) == 5)
{
range_add = worksheet.get_Range("X" i.ToString(), "AQ"i.ToString() );
}
System.Array values = (System.Array)range_add.Cells.Value;
string[] str = ConvertToStringArray(values);
for (int l = 0; l < str.Length; l++)
Console.WriteLine(l +" "+str[l]);
name = str[0];
lang_add = str[1];
price = str[2];
description = str[3];
Console.WriteLine(name + " " + lang_add + " " + price + " " + description);
addfile();
name = "";
lang_add = "";
price = "";
description = "";
}
}
You may want to consider using Int32.TryParse instead of blindly calling
Convert.ToInt32()
- if the cell in row F doesn't contain a number, your program's going to throw an exception that you could otherwise deal with.The question seems a bit... simple? You know your starting point, you know how far you're looking to go (
number * 4
) and I assume you know how to write afor
loop. Is there something else here?