C # Reading CSV files

Source: Internet
Author: User

C # Reading CSV files
Many projects need to operate the CSV file. I see many people will code to read the first row of the CSV file and explain the values of each column,

This is relatively difficult,

First, developers are required to be familiar with string processing,

Second, we need to have a good understanding of the CSV file structure, which is difficult and the quality of the Code to be written must be tested for a period of time,

But there is actually a simpler method, that is, using Microsoft's text driver to access CSV files in the form of tables.

The Code is as follows:

Public DataTable GetCsvData (string filePath, string fileName)

{

String path = filePath + "\" + fileName + ". csv ";

String connString = @ "Driver = {Microsoft Text Driver (*. txt; *. csv)}; Dbq =" + filePath + "; Extensions = csv ";

Try

{

Using (OdbcConnection odbcConn = new OdbcConnection (connString ))

{

OdbcConn. Open ();

OdbcCommand oleComm = new OdbcCommand ();

OleComm. Connection = odbcConn;

OleComm. CommandText = "select * from [" + fileName + "# csv]";

OdbcDataAdapter adapter = new OdbcDataAdapter (oleComm );

DataSet ds = new DataSet ();

Adapter. Fill (ds, fileName );


OdbcConn. Close ();

Return ds. Tables [0];


}

}

Catch (Exception ex)

{

Throw ex;

}

}


 

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.