We help IT Professionals succeed at work.
Get Started

How would I export a DataTable to a text file and define the string length and the start position of each column ?

GD_GRAY
GD_GRAY asked
on
82 Views
Last Modified: 2015-06-26
My issue is I need to build a text file with a specific format. Each row (line) in the text file can only be 111 characters long and each row (line) in the text file will represent a single row from the DataTable.

DataTable:
Column1 | Column2 | Column3 | Column4
My            |Phone #   |is                |8000000000
My            |Phone #   |is                |9990000000


TextFile:

Column1 starts at position 0, Column2 starts at position 2, Column3 starts at position 40, Column4 starts at position 90,

MyPhone#                                is                                                8000000000          
MyPhone#                                is                                                9990000000          


I am able to use
public void ExportDataTabletoFile(DataTable datatable, string delimited, bool exportcolumnsheader, string file)

{
    StreamWriter str = new StreamWriter(file, false, System.Text.Encoding.Default);
    if (exportcolumnsheader)
    {
        string Columns = string.Empty;
        foreach (DataColumn column in datatable.Columns)
        {
            Columns += column.ColumnName + delimited;
        }
        str.WriteLine(Columns.Remove(Columns.Length - 1, 1));
    }
    foreach (DataRow datarow in datatable.Rows)
    {
        string row = string.Empty;
 
        foreach (object items in datarow.ItemArray)
        {
 
            row += items.ToString() + delimited;
        }
        str.WriteLine(row.Remove(row.Length - 1, 1));
 
    }
    str.Flush();
    str.Close();
 
}

Open in new window


And call it like
ExportDataTabletoFile(GetTable(), " ,", false, file);

Open in new window


but that is all I can come up with.

result:

My,Phone#,is,8000000000
My,Phone#,is,9990000000

Can any one expand on this for me.

Thanks.....
Comment
Watch Question
Retired
CERTIFIED EXPERT
Distinguished Expert 2017
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE