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

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.....
GD_GRAYAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Hi GD_GRAY;

The below code snippet is part of your code modify to write a formatted line. The format specifier such as {1,-37}, will format the second item in the array with index 1 to always have 37 character position and left justified, - means left justified. Now your sample output did not have a delimiter and seeming each column is a fixed width you do not need a delimiter. You can also apply this same idea with the header names.

// Get each row of the DataTable
foreach (DataRow datarow in datatable.Rows)
{
    // Holds the formatted string of the row
    string row = string.Empty;
    // Holds the column values of the row     
    object[] col = datarow.ItemArray;
    // Format the line of the file with the correct field width
    row = String.Format("{0,2}{1,-37}{2,-50}{3,-10}", col );

    // Write the formatted line to the file
    str.WriteLine(row.Remove(row.Length - 1, 1));

}
str.Flush();
str.Close();

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David Johnson, CD, MVPOwnerCommented:
you will have to build your strings by yourself
Do you want
my,phone,                    is,           ######## or
column1start = 0
column2start=4
column3start=40
column4start-90
output = column1.text + ","
spaces = column2start - strlen(output)
spacer = ""
for (I=0;i<spaces;i++){spacer += " ";}
output= output + spacer + column2.txt + ",";
spaces = column3start - strlen(output);
spacer = ""
for (I=0;i<spaces;i++){spacer += " ";}
output= output + spacer + column3.txt + ",";
spaces = column4start - strlen(output);
spacer = ""
for (I=0;i<spaces;i++){spacer += " ";}
output= output + spacer + column4.txt;
write(output);
GD_GRAYAuthor Commented:
Wow......

Thank you !
GD_GRAYAuthor Commented:
Soto Sir,

Any way to get the string format values from a list, or a datatable column ?
Fernando SotoRetiredCommented:
To your followup question, "Any way to get the string format values from a list, or a datatable column ?", the format specifier is just a string and can be stored in a list or any object that can store a string in. When you are ready to use it retrieve it from where you are storing it and place it in a string variable and use that string variable where the specifier is now.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.