tags:

views:

502

answers:

5

I want to put some numbers from Excel to array. Let's say I have an Excel file with some numbers like this:

23 34 1 3 100 56 45 43 56 4 87 6 89 9

this is just one column in excel (or any file) And i want to put those numers in arraylist as integer numbers, i dont need the result as one number but all those numbers to be in int value.

Any help please ?

A: 

You could also export into a file format, ie xml or csv, and then parse this from your c# program.

DanDan
+1  A: 

Assuming that the above is a string (and the source does not matter), you can do the following:

string s = "23 34 1 3 100 56 45 43 56 4 87 6 89 9";
string[] numbers = s.Split(' ');

ArrayList numberList = new ArrayList();
int i;

foreach (String num in numbers)
{
    if (Int32.TryParse(num, out i))
        numberList.Add(i);
    else
        Console.WriteLine("'{0}' is not a number!", num);
}

listBox1.DataSource = numberList;

I suggest using List<int> instead of ArrayList for type safety.

The following code reads all values from an Excel sheet into a data set using a DB connection. You can then pick the value needed.:

String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1ReadOnly=False\"";

OleDbConnection objConn = new OleDbConnection(sConnectionString);

objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + sheetname + "$]", objConn);

OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;

DataSet dsExcelContent = new DataSet();
objAdapter1.Fill(dsExcelContent);

objConn.Close();

EDIT
You did not specify the exact source for the string, so if this question is about how to read a file or how to import data from an Excel spreadsheet, you should probably rephrase your question a little.

EDIT 2
Replaced List<int> by ArrayList on OP's wish (against better design).

EDIT 3
Added a new line to show the OP how to use the ArrayList as a data source for a ListBox...

EDIT 4
Added code to read Excel sheet using OleDB.

Thorsten Dittmar
i can not change my program now, it has more than 100 lines and i did it with ArrayList, Any idea how to do that ?
AXheladini
Yes. Replace List<int> with ArrayList.
Thorsten Dittmar
the problem is that i have a excel file with more than 1000 numbers in one column, and i want those numbers to be stored in array list. If you can write me some lines how to do all this it will be good?
AXheladini
That's what the above code does, only that I've initialized the string s with fixed content. In your case, s would contain the cell's content.
Thorsten Dittmar
@AXheladini You should really think about changing ArrayList to List<T>. This can (usually) be done easily with only a few hundred or thousand lines of code and you will gain much code quality.
Daniel Brückner
I try to put the value of the ArrayList in ListBox, all i get is just the first number (23). string s = "23 34 1 3 100 56 45 43 56 4 87 6 89 9"; string[] numbers = s.Split(' '); ArrayList numberList = new ArrayList(); int i; foreach (String num in numbers) { if (Int32.TryParse(num, out i)) { numberList.Add(i); this.listBox1.DataSource = numberList; } else Console.WriteLine("'{0}' is not a number!", num);
AXheladini
Of course. You must set the data source after the loop. Otherwise the ListBox will not get notified about the new elements.
Thorsten Dittmar
Thanks made, its good now, One more solution and is done, How to read the column from Excel in the best way, do you have any code for that ? i want this string s = "23 34 1 3 100 56 45 43 56 4 87 6 89 9";to be taken from excel or some file. This one and all will be done?
AXheladini
Well, I can hardly answer "from excel or some file", because accessing an Excel file is different from accessing a CSV or XML file. You have to decide what you want.
Thorsten Dittmar
let it be from excel ?
AXheladini
Can you post me some code for Excel ??
AXheladini
Edited my reply and added code for reading Excel file. Use Google to find out how to address a specific column when selecting the values. This should also be possible.
Thorsten Dittmar
I have problems now to assign the result of the dataset to string s ?
AXheladini
Any solution how to join the first part with the second part ?
AXheladini
string s = dsExcelContent.Tables[<number of table>].Rows[y][x].ToString(); I guess you'll have to figure out the indices for yourself.
Thorsten Dittmar
I dont know why i can not fix this, i get only the firs number from that column ? By the way thanks for the help
AXheladini
Use the debugger to inspect the dataset. Maybe the numbers are not in one column as you said. Unfortunately, there's nothing more I can do for you here - the rest you'll have to figure out yourself ;-)
Thorsten Dittmar
Ok thanks, you helped me with this problem. Kind Regards
AXheladini
A: 

i dont have problem reading from excel i have problem when i put those numbers in ArrayList, This way numbers are stored in the ArrayList as string so as output i get one string like that: 23443223564563457, wat i want is to store those numbers as integer 1, 4, 100, 300, 59, 6, ..............

It will be good if someone can write me some code ?

AXheladini
do not add coments/updates on the question as answers, instead edit your original post to clrify (and then delete this answer).In this way things are clearer for people reading the question anew
ShuggyCoUk
+1  A: 

This is quite easy be splitting the string and parsing each item into a list.

String input = "23 34 1 3 100 56 45 43 56 4 87 6 89 9";

List<Int32> result = input
    .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(i => Int32.Parse(i))
    .ToList();

Note that this code has no error handling. If an item is not a valid integer, an exception will be thrown. You can handle this case by using Int32.TryParse(). You best do this without LINQ, but you can use the following inefficent LINQ code, too.

Int32 dummy;
List<Int32> result = input
    .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
    .Where(i => Int32.TryParse(i, out dummy))
    .Select(i => Int32.Parse(i))
    .ToList();

Without LINQ.

String input = "23 34 1 3 100 56 h45 43 56 4 87 6 89 9";

Int32 dummy;
List<Int32> result = new List<Int32>();

foreach (String item in input.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
    Int32 number;
    if (Int32.TryParse(item, out number))
    {
        result.Add(number);
    }
    else
    {
        // Handle invalid items.
    }
}
Daniel Brückner
i can not use LINQ since i am with VS 2005
AXheladini
Then use the 3rd code snippet that Daniel provided. It doesn't use linq, and will work in .NET 2.0. List<T> is part of generics.
Anonymous Type
A: 

With this Code i only get the first number in the listbox, whats the problem Thorsten Dittmar ?

string s = "23 34 1 3 100 56 45 43 56 4 87 6 89 9"; string[] numbers = s.Split(' ');

        ArrayList numberList = new ArrayList();

        int i;

        foreach (String num in numbers)
        {
            if (Int32.TryParse(num, out i))
            {
                numberList.Add(i);
                this.listBox1.DataSource = numberList;
            }
            else
                Console.WriteLine("'{0}' is not a number!", num);
AXheladini
See my reply above...
Thorsten Dittmar