Solved

C#  loop through data table rows - skips first row

Posted on 2013-06-30
5
2,094 Views
Last Modified: 2013-07-05
I am creating a datatable to write from an Excel spreadsheet to a csv file.

The code skips the first data row, the column headers. The column headers do not get written to the csv.  Sample spreadsheet attached.

The code:
---------------------------
convertExcelToCSV(@"c:\keys\book2.xls", "Sheet1", @"c:\keys\target.csv")

---------------------------
static void convertExcelToCSV(string sourceFile, string worksheetName, string targetFile)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";

            OleDbConnection conn = null;
            StreamWriter wrtr = null;
            OleDbCommand cmd = null;
            OleDbDataAdapter da = null;
           
            try
            {
                conn = new OleDbConnection(strConn);
                conn.Open();
                cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
                cmd.CommandType = CommandType.Text;
                wrtr = new StreamWriter(targetFile);
                da = new OleDbDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                for (int x = 0; x < dt.Rows.Count; x++)
                {
                    string st = dt.Rows[x].ToString();
                    for (int y = 0; y < dt.Columns.Count; y++)
                    {
                        if (y > 0)
                        {
                            rowString += ",";
                        }
                        {
                            rowString += "\"" + dt.Rows[x][y].ToString() + "\"";
                           
                        }
                    }
                    wrtr.WriteLine(rowString);
                }
                MessageBox.Show("Done! Your " + sourceFile + " has been converted into " + targetFile + ".");
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }

            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                    conn.Dispose();
                    cmd.Dispose();
                    da.Dispose();
                    wrtr.Close();

                wrtr.Dispose();

            }

        }
Book2.xls
0
Comment
Question by:Delta7428
  • 3
  • 2
5 Comments
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
Comment Utility
This piece of code prints column names:

            DataTable dt = new DataTable();
            Type typeInt32 = Type.GetType("System.Int32");
            Type typeString = Type.GetType("System.String");
            DataColumn dc1 = new DataColumn("A",typeInt32);
            DataColumn dc2 = new DataColumn("B",typeString);
            DataColumn dc3 = new DataColumn("C", typeString);
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);

            string rowString = "";

            for (int y = 0; y < dt.Columns.Count; y++)
            {
                if (y > 0)
                {
                    rowString += ",";
                }
                rowString += dt.Columns[y].ColumnName;


            }
                System.Diagnostics.Debug.WriteLine(rowString);

Open in new window



Output:
A,B,C

Open in new window

0
 

Author Comment

by:Delta7428
Comment Utility
Thanks.  I will test your code in the morning.

But thinking ... Maybe the data table wasn't the best way to go here.   Maybe I have a spreadsheet that doesn't have column names and the the first row is a data row, not column names.    A datatable always assumes the first row is column names ... makes sense, but may not be what I need for other spreadsheet formats.

Seems like a lot of hoopla to get that first row.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
0
 

Author Comment

by:Delta7428
Comment Utility
Thanks anarki.  I got pulled off on another assignment.  I will get back to you in a day or 2.
0
 

Author Comment

by:Delta7428
Comment Utility
I posted a follow up question .. copied and pasted and submitted it by mistake...  Decided to take another look at resolving followup question on my own.  Looks like I can't delete a comment so I wiped it out and replaced it with this.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now