How to convert a DataTable into a CSV file in C # _c# tutorial

Source: Internet
Author: User

A DataTable is used in a. NET project to cache data, and a DataTable represents a table of data in memory. CSV file was first used in a simple database, because of its simple format, and has a strong openness, so initially swept the map home as their own Atlas of the tag. A CSV file is a plain text file, and each row represents many of the attributes of a picture.

Using C # to transform a DataTable into a CSV file in a. NET project now provides a more general approach, as follows:

<summary>///convert DataTable to csv file///</summary>///<param name= "DT" >DataTable</param>///&  Lt;param name= "FilePath" > File path </param> public static void Savecsv (DataTable dt, string filePath) {FileStream fs =
Null
StreamWriter sw = null; try {fs = new FileStream (filePath + dt).
TableName + ". csv", FileMode.Create, FileAccess.Write);
SW = New StreamWriter (FS, Encoding.default); var data = string.
Empty; Writes out the column name for (var i = 0; i < dt. Columns.count; i++) {data + + dt. Columns[i].
ColumnName; if (i < dt.
COLUMNS.COUNT-1) {Data + = ",";}} Sw.
WriteLine (data); Write out the row data for (var i = 0; i < dt.) Rows.Count; i++) {data =string.
Empty; for (var j = 0; j < dt.) Columns.count; J + +) {data + = dt. ROWS[I][J].
ToString (); if (J < dt.
COLUMNS.COUNT-1) {Data + = ",";}} Sw.
WriteLine (data); } catch (IOException ex) {throw new IOException (ex.
Message, ex); finally {if (SW!= null) SW.
Close (); if (fs!= null) fs.
Close (); }
}

The above is a small set to introduce C # will be a DataTable conversion to CSV file method, I hope to help you, if you have any questions please give me a message, small set would promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.