Save data in txt/excel format from 0 self-paced c#03--file streams

Source: Internet
Author: User
Tags log log
This paper mainly introduces DataTable, log logs, file stream FileStream, StreamWriter class, and saves the data in TXT and Excel format.

1. Create a testdatatable class

The CreateTable () method creates a data Table,savetabletoexcel (string fileName) method to save the data table as an Excel format file named filename, CreateDirectory ( String fileName) method to check if a file exists and, if it does not exist, automatically creates one.

Class Testdatatable:datatable {public void createtable () {this.            Columns.Add ("Time (s)", System.Type.GetType ("System.String")); This.            Columns.Add ("Ch", System.Type.GetType ("System.String")); This.                        Columns.Add ("BER", System.Type.GetType ("System.String"));                        const int length1 = 4;            const int length2 = 10;            int[][] data = new int[length1][];            First Data data[0] = new Int[length2] {13, 25, 21, 33, 28, 39, 43, 36, 42, 36};            Second data data[1] = new Int[length2] {20, 13, 10, 5, 15, 7, 10, 14, 19, 20};            Third data data[2] = new Int[length2] {78, 92, 65, 83, 90, 59, 63, 72, 88, 98};            Fourth data data[3] = new Int[length2] {45, 49, 39, 47, 52, 76, 67, 51, 57, 67};                    for (int i = 0, i < length2; i++) {for (int j = 0; J < Length1; J + +) { DataRow Dr = this.                    NewRow ();                    Dr[0] = i + 1;                    Dr[1] = j;                    DR[2] = Data[j][i]; This.                Rows.Add (DR); }}} public void Savetabletoexcel (string filename) {createdirectory (filename)            ;            StringBuilder title = new StringBuilder ();            FileStream FileStream = new FileStream (FileName, FileMode.OpenOrCreate);            StreamWriter writer = new StreamWriter (new BufferedStream (FileStream), System.Text.Encoding.Default); for (int i = 0; I < this. Columns.count; i++) {title. Append (this. Columns[i]. ColumnName + "\ t"); Field: Automatically jumps to the next cell} title.            Append ("\ n"); Writer.            Write (title); foreach (DataRow row in this.)                Rows) {StringBuilder content = new StringBuilder (); for (int i = 0; I < this. Columns.count; i++) {conTent. Append (Row[i] + "\ t");//content: Automatically jumps to the next cell} content.                Append ("\ n"); Writer.            Write (content); } writer.            Close ();        Filestream.close (); public void CreateDirectory (string fileName) {DirectoryInfo DirectoryInfo = Directory.getparen            T (FileName);            if (!directoryinfo.exists) {directoryinfo.create (); }        }      }

2. Create Log class

Defines the file name filename as a property of the class and assigns a value when the constructor is constructed. The Savelogtotxt (string info) method stores data info in a TXT file named filename. Same CreateDirectory () method to check if the file exists

Class Log {private string fileName;            public string FileName {set {this.filename = value;            } get {return this.filename;            }} public Log (string filename) {this.filename = FileName;        CreateDirectory ();              public void Savelogtotxt (string info) {StreamWriter writer = null;            FileStream FileStream = null;                  try {System.IO.FileInfo FileInfo = new System.IO.FileInfo (this.filename);                      if (!fileinfo.exists) {fileStream = Fileinfo.create ();                  writer = new StreamWriter (fileStream); } else {fileStream = Fileinfo.open (Filemode.append, Fileaccess.wri                      TE); writer = new StreamWriter (filestrEAM); } writer.            WriteLine (info); } finally {if (writer! = null) {writer.                      Close (); Writer.                      Dispose ();                      Filestream.close ();                  Filestream.dispose (); }}} public void CreateDirectory () {DirectoryInfo DirectoryInfo = D Irectory.              GetParent (This.filename);              if (!directoryinfo.exists) {directoryinfo.create (); }          }      }

3. Calling the class method to save data

Instantiate the class, create the data table, save the table in TXT format and Excel format, and name the time.

Testdatatable dt = new testdatatable ();d T. CreateTable ();d T. Rows.clear (); Clears all rows of data in table DateTime startTime = DateTime.Now;  Log log = new log (@ "log\" + starttime.tostring ("YYYYMMDDHHMMSS") + ". txt");//time file name, existence exe folder under the log folder for (int i = 0; i < 4; i++) {    DataRow dr = dt. NewRow ();    DR[0] = (int) second;    DR[1] = i;    DR[2] = Berbychannel[i]. ToString ("E2");    Dt. Rows.Add (DR);//Add new row to data table    String info = string. Format ("{0}: Time (s): {1}, Ch: {2}, BER: {3}", DateTime.Now, Dr[0], dr[1], dr[2]);    Log. Savelogtotxt (info);//Save As TXT format                    }//Save as Excel format string fileName = @ "testrecord\" + starttime.tostring ("Yyyymmddhhmmss" ) + ". xls";d T. Savetabletoexcel (fileName);//Name of the file in time, the Testrecord folder in the folder where EXE exists

The above is from 0 self-study c#03--file stream to save data to txt/excel format content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.