Converts a able to a CSV file, and a DataTable to a csv file.

Source: Internet
Author: User

Converts a able to a CSV file, and a DataTable to a csv file.

DataTable is used in. net projects to cache data. DataTable indicates a table with data in memory. CSV files were first used in a simple database. Because of their simple format and strong openness, they were first marked by their own gallery by the scanner. A csv file is a plain text file. Each line represents many attributes of an image.

Using C # In the. net project to convert a able to a CSV file provides a common method. The Code is as follows:

 

/// <Summary> /// convert the DataTable to a CSV file // </summary> /// <param name = "dt"> DataTable </param> // /<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; // Write 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 each row of 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 ();}}

 

Related Article

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.