Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataTable to Txt

Status
Not open for further replies.

sahernandez

Programmer
Oct 1, 2002
69
SV
Anybody know how can I do this,
I have a DataTeble("Table") and this table have

Field1 Field2 Field3
A B C
D E F

I want to transform this table to TXT , separate by comma or by TAB
A,B,C
D,E,F

OR

A B C
D E F

anybody know how can I do that, I have to save this into the client.

Thxs
Alexander

 
You need a custom function that will simply iterate the DataTable and build up a string that's in the format you need. Here's a couple of methods that you can use if you like:

Code:
public static string FromDT(DataTable t)
{
	return FromDT(t,false);
}
public static string FromDT(DataTable t, bool firstRowAreNames)
{
	StringBuilder sb = new StringBuilder();
	if(firstRowAreNames)
	{
		for(int i = 0; i < t.Columns.Count; i++)
		{
			sb.Append(t.Columns[i].ColumnName);
			if(i < t.Columns.Count - 1)
				sb.Append("\t");
		}
		sb.Append(Environment.NewLine);
	}
	for(int i = 0; i < t.Rows.Count; i++)
	{
		for(int j = 0; j < t.Columns.Count; j++)
		{
			sb.Append(t.Rows[i][j].ToString());
			if(j < t.Columns.Count - 1)
				sb.Append("\t");
		}
		sb.Append(Environment.NewLine);
	}
	return sb.ToString();
}

To use, just call it:

string tabDelimitedText = FromDT(yourDataTable);

enjoy.

-paul

penny.gif
penny.gif

The answer to getting answered -- faq855-2992
 
Thxs Link9.

But I guess there is another way to do, cause I don't want to loop this for each column.

I know that put the information from DataTable into Array or ArrayList,and then use Join function I can avoid to loop for each column, but I don't know how to use it

Thxs again Link9

 

Dim myRow As DataRow
For Each myRow In OraTb_Main.Rows

Dato_TXT &= LTrim(Join(myRow.ItemArray),ControlChars.Tab)) & ControlChars.NewLine

Next

Response.Clear()
Response.ContentType = "text/plain"
Response.ContentEncoding = System.Text.Encoding.ASCII
Response.Write(Dato_TXT)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top