tags:

views:

271

answers:

5

What i need id to take the first column of an excel file and put that column in a string variable but numbers that will be taken from excel to be separated with blank space.

For Example:

Excel file:

1 3 4 56 76 7 876 23 43 (in column)

and string in C#

string number = "1 3 4 56 76 7 876 23 43"

Any code will help me I have made the connection with excel file and i have created the dataset/datatable but now i can not take those numbers as the sample above ?

A: 

Have a link - Reading Excel Document

adatapost
A: 

Here's what I would do...first open the spreadsheet with this code.

xlApp = New Excel.Application
filePath = "FILENAME"
xlWorkBook = xlApp.Workbooks.Open(filePath)
xlWorkSheet = xlWorkBook.Worksheets(1)

Then read through the column like this

For data As Integer = 0 To 8
    Dim obj As Excel.Range = CType(xlWorkSheet.Cells(data, 1), Range)
    If obj.Value IsNot Nothing Then
        MyArray(data) = obj.Value
    Else
        Exit Do
    End If
Next

Then you should have all your data in MyArray then loop through and create a string with spaces and you should be good. This code is in VB but it should give you a good idea of the commands and structure to use.

novacara
A: 

You just want to loop through the rows in the Dataset now:

var numberStr = EmptyStr;
foreach (DataRow dr in MyDataSet.Tables[0].Rows)
{
    numberStr = EmptyStr ? numberStr += dr[0].ToString() : numberStr += " " + dr[0].ToString(); 
}

Updated Solution

private void Form1_Load(object sender, EventArgs e) 
{
    String s = String.Empty;
    String sConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=unsorted.xls;Extended Properties=""Excel 12.0;HDR=NO;""";
    using (OleDbConnection conn = new OleDbConnection(sConnectionString)) 
    {
        conn.Open();
        DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
        foreach (DataRow schemaRow in schemaTable.Rows) 
        {
            string sheet = schemaRow["TABLE_NAME"].ToString();
            OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
            cmd.CommandType = CommandType.Text;

            DataTable outputTable = new DataTable(sheet);
            output.Tables.Add(outputTable);
            new OleDbDataAdapter(cmd).Fill(outputTable);
        }

        // populate string with value from rows
        foreach (DataRow dr in MyDataSet.Tables[0].Rows)
        {
           s = String.Empty ? s += dr[0].ToString() : s += " " + dr[0].ToString(); 
        }       

        dataGridView1.DataSource = dsExcelContent1;        
        objConn.Close();
    }

    this.label1.Text = s;        
    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);
        }        
    }        
    this.listBox1.DataSource = numberList;
}
James
Can you help me to implement this in my code ?
AXheladini
+2  A: 

If you have the data in a datset...you can do something like this....

////TRY THIS!!!

DataSet dsExcelContent = new DataSet();


     //Fill from db
        //
         StringBuilder builder = new StringBuilder();
        foreach (DataRow row in dsExcelContent.Tables[0].Rows)
        {


            builder.Append(row[0].ToString());
            builder.Append(" ");


        }
        Console.WriteLine(builder.ToString());

.....More exact to your code....

   OleDbConnection objConn = new OleDbConnection(sConnectionString);

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

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

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

        dataGridView1.DataSource = dsExcelContent1;
        objConn.Close();

        int test = dsExcelContent.Tables[0].Rows.Count;

StringBuilder builder = new StringBuilder();

        foreach (DataRow row in dsExcelContent.Tables[0].Rows)
        {

            builder.Append(row[0].ToString());
            builder.Append(" ");


        }
            //s has the data you want.....
        string s = builder.ToString();

            //REST OF YOUR CODE.....
CSharpAtl
How can i combine your code and mine and o achieve what i need /?
AXheladini
Can you help me how to implement that in my code ?
AXheladini
I just added some more hopefully it helps...
CSharpAtl
You do not have to manually create the DataTable...when you call Fill on the adapter it will create the table
CSharpAtl
Error 1 foreach statement cannot operate on variables of type 'System.Data.DataTable' because 'System.Data.DataTable' does not contain a public definition for 'GetEnumerator' C:\UsersI get this error now ? \Administrator\Documents\Visual Studio 2005\Projects\Merge - JoinTest\Merge - JoinTest\Form1.cs 42 12 Merge - JoinTest
AXheladini
This is the error that i get now
AXheladini
replace dsExcelContent.Tables[0] to replace dsExcelContent.Tables[0].Rows....my original code works on mine..you might be using older version of framework.
CSharpAtl
replace dsExcelContent.Tables[0] with dsExcelContent.Tables[0].Rows in the foreach
CSharpAtl
i replaced that and now ad a result i get only the last number of the excel column ?
AXheladini
please post your new code....
CSharpAtl
is all your excel data in 1 datatable? can you debug and look at the dataset/datable and make sure all data is in there?
CSharpAtl
i just tested the dataset with this code: int test = dsExcelContent.Tables[0].Rows.Count; and i see that all 19 rows are there ? What can be the problem ??
AXheladini
i just edited my Code up there ?
AXheladini
so you are not getting all the data from 1 row? Is it possible that you only have 1 column of data per row?
CSharpAtl
I reread your question...hold on....I was not appending the 1st column...I was appending each column....
CSharpAtl
o i see we must append each row right ?
AXheladini
check the new code...
CSharpAtl
Still the same only the last number ?
AXheladini
sorry....try that last edit....had to move the WriteLine out of the loop in the newest code...
CSharpAtl
you need to set your string s = builder.ToString(); OUTSIDE the loop.....not inside. You assignment there is like my Console.WriteLine statment...
CSharpAtl
yes i recognized that but now i get this error: Error 1 The name 'builder' does not exist in the current
AXheladini
it works great i just declared the sting outside the loop and now works great> Thanks bro, you helped me very well
AXheladini
YES...just made that change...sorry doing this outside an editor...:D
CSharpAtl
Can you declare my answer as the solution?
CSharpAtl
yes of course, i just did that Thanks oe more time
AXheladini
No problem...glad we got it figured out...
CSharpAtl
A: 

private void Form1_Load(object sender, EventArgs e) { String sConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=unsorted.xls;Extended Properties=""Excel 12.0;HDR=NO;""";

        OleDbConnection objConn = new OleDbConnection(sConnectionString);

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

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

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

        dataGridView1.DataSource = dsExcelContent1;
        objConn.Close();

        int test = dsExcelContent.Tables[0].Rows.Count;

       foreach(DataRow row in dsExcelContent.Tables[0].Rows)
        {
            StringBuilder builder = new StringBuilder();
            foreach (DataColumn col in dsExcelContent.Tables[0].Columns)
            {
                builder.Append(row[col].ToString());
                builder.Append(" ");
            }

            string s = builder.ToString();

            this.label1.Text = s;

            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);
            }

            this.listBox1.DataSource = numberList;

        }






    }
}
AXheladini
Are you sure the data is in the table you created? Seems like if you are not going to used Typed DataSets...you will have to manually add the table to the dataset....dsExcelContent.Tables.Add(dsExcelContent1);
CSharpAtl