How to transfer DataTable to TXT and CSV files in C #
This article mainly introduces the C# how to achieve DataTable to TXT, CSV file related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this C# how to achieve DataTable to TXT, CSV file article will have a harvest, let's take a look.
Transfer to TXT file public object DataTableToTXT (DataTable vContent, string vOutputFilePath) {object resObj; StringBuilder sTxtContent; try {if (File.Exists (vOutputFilePath)) File.Delete (vOutputFilePath); sTxtContent = new StringBuilder () / / data foreach (DataRow row in vContent.Rows) {for (int I = 0; I < vContent.Columns.Count; iTunes +) {sTxtContent.Append (row [I] .ToString () .Trim ()) STxtContent.Append (I = = vContent.Columns.Count-1? "\ r\ n": "\ t");}} File.WriteAllText (vOutputFilePath, sTxtContent.ToString (), Encoding.Unicode); resObj = new object [] {0, "OK"} } catch (Exception ex) {resObj = new object [] {0, "OK"};} return resObj;} to .CSV file
Converting DataTable to CSV file is a common form of conversion, mainly by traversing each line of Table, then traversing each column of each row, realizing the reading of data, and then separating each field data of Table with a separator, writing the read characters to the CSV file. Here, each field is separated by a comma, and each line is separated by a newline character. The implementation code is as follows:
Public ExecutionResult DataTableToCsv (System.Data.DataTable vContent, string vOutputFilePath) {ExecutionResult sResult = new ExecutionResult (); System.Text.StringBuilder sCsvContent; try {sCsvContent = new System.Text.StringBuilder (); / / Field for (int I = 0; I < vContent.Columns.Count IContent.ColumnName) {sCsvContent.Append (vContent.ColumnName); sCsvContent.Append (I = = vContent.Columns.Count-1? "\ r\ n": ",") } / / data foreach (System.Data.DataRow row in vContent.Rows) {for (int I = 0; I < vContent.Columns.Count; iTunes +) {sCsvContent.Append (row [I] .ToString () .Trim ()) SCsvContent.Append (I = = vContent.Columns.Count-1? "\ r\ n": ",");} File.WriteAllText (vOutputFilePath, sCsvContent.ToString (), Encoding.UTF8); sResult.Status = true } catch (Exception ex) {sResult.Message = ex.Message; sResult.Status = false;} return sResult;} this is the end of the article on "how to convert DataTable to TXT and CSV files in C#". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to convert DataTable to TXT and CSV files". If you want to learn more knowledge, you are welcome to follow the industry information channel.