WPF Export CSV file

Source: Internet
Author: User

1  /// <summary>2         ///writing data from a DataTable to a CSV file3         /// </summary>4         /// <param name= "DT" >provide a DataTable for saving data</param>5         /// <param name= "FileName" >file path for CSV</param>6          Public Static voidsavecsv (DataTable DT)7         {8SaveFileDialog OBJSFD =NewSaveFileDialog () {DefaultExt ="CSV", Filter ="CSV Files (*.csv) |*.csv| Excel XML (*.xml) |*.xml| All Files (*. *) |*.*", FilterIndex =1 };9             if(Objsfd.showdialog () = =true)Ten             { One                 stringStrformat =Objsfd.filename; AFileInfo fi =NewFileInfo (Strformat); -                 if(!fi. directory.exists) -                 { the fi. Directory.create (); -                 } -FileStream fs =NewFileStream (Strformat, System.IO.FileMode.Create, System.IO.FileAccess.Write); -                 //StreamWriter sw = new StreamWriter (FS, System.Text.Encoding.Default); +StreamWriter SW =NewStreamWriter (FS, System.Text.Encoding.UTF8); -                 stringdata =""; +                 //write out the column name A                  for(inti =0; i < dt. Columns.count; i++) at                 { -Data + =dt. Columns[i]. Columnname.tostring (); -                     if(I < dt. Columns.count-1) -                     { -Data + =","; -                     } in                 } - SW. WriteLine (data); to                 //write each row of data +                  for(inti =0; i < dt. Rows.Count; i++) -                 { thedata =""; *                      for(intj =0; J < dt. Columns.count; J + +) $                     {Panax Notoginseng                         stringstr =dt. ROWS[I][J]. ToString (); -str = str. Replace ("\"","\"\"");//Replace the colon with the English colon to be replaced by two colons the                         if(str. Contains (',') || Str. Contains ('"') +|| Str. Contains ('\ r') || Str. Contains ('\ n'))//need to enclose the comma with a colon line break in quotation marks A                         { thestr =string. Format ("\ "{0}\"", str); +                         } -  $Data + =str; $                         if(J < dt. Columns.count-1) -                         { -Data + =","; the                         } -                     }Wuyi SW. WriteLine (data); the                 } - SW. Close (); Wu FS. Close (); -             About             } $  -}
1   /// <summary>2     ///reading data from a CSV file into a DataTable3     /// </summary>4     /// <param name= "FileName" >csv file path</param>5     /// <returns>returns a DataTable that reads CSV data</returns>6      Public StaticDataTable Opencsv (stringFilePath)7     {8Encoding Encoding = Common.gettype (FilePath);//Encoding.ascii;//9DataTable dt =NewDataTable ();TenFileStream fs =NewFileStream (FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); One          A         //StreamReader sr = new StreamReader (FS, Encoding.UTF8); -StreamReader sr =NewStreamReader (fs, encoding); -         //string filecontent = Sr. ReadToEnd (); the         //encoding = Sr. currentencoding; -         //record a row of records per read -         stringStrLine =""; -         //record the contents of each field in each row of records +         string[] Aryline =NULL; -         string[] Tablehead =NULL; +         //number of marked columns A         intColumnCount =0; at         //indicates if the first line is read -         BOOLIsFirst =true; -         //read data in CSV row by line -          while((StrLine = Sr.) ReadLine ())! =NULL) -         { -             //strLine = Common.convertstringutf8 (strLine, encoding); in             //strLine = Common.convertstringutf8 (strLine); -  to             if(IsFirst = =true) +             { -Tablehead = Strline.split (','); theIsFirst =false; *ColumnCount =tablehead.length; $                 //Create ColumnsPanax Notoginseng                  for(inti =0; i < ColumnCount; i++) -                 { theDataColumn DC =NewDataColumn (Tablehead[i]); + dt. Columns.Add (DC); A                 } the             } +             Else -             { $Aryline = Strline.split (','); $DataRow dr =dt. NewRow (); -                  for(intj =0; J < ColumnCount; J + +) -                 { theDR[J] =Aryline[j]; -                 }Wuyi dt. Rows.Add (DR); the             } -         } Wu         if(Aryline! =NULL&& aryline.length >0) -         { AboutDt. Defaultview.sort = tablehead[0] +" "+"ASC"; $         } -          - Sr. Close (); - FS. Close (); A         returnDT; +     } the}

I found a lot of ================================================================.

=============================================================================================================== ================= turn from https://www.cnblogs.com/Clin/archive/2013/03/14/2959022.html===================

=============================================================================================================== =========

WPF Export CSV file

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.