SoFunction
Updated on 2025-03-07

C# implements quick reading of txt text data into excel

Today, a function is implemented to transfer the data in txt to the excel table and serve as a data source for matlab. Collect some C# operators to operate Excel. The steps are as follows:

Download one cited in the project.

Write the code as follows:

      string path = "c://date//";
      StreamReader sr = new StreamReader(path);
      string strLine = ();
      int rowNum = 1;
      object missing = ;

      ApplicationClass app = new ApplicationClass();

      (true);

      Workbook book = (Workbook);
      Worksheet sheet = (Worksheet);
      while (!(strLine))
      {
        string[] tempArr;
        tempArr = (',');
        for (int k = 1; k <= ; k++)
        {
          [rowNum, k] = tempArr[k - 1];

        }
        strLine = ();
        rowNum++;

      }

      //Save Excel file      ("D://");
      //Close the file      (false, missing, missing);
      //Exit excel      ();
      ("Conversion was successful!");

The above code can implement functions. Since there are 60,501 lines of data in txt, the amount of data is too large. I estimated that it will take about 2-3 minutes to use the above code to go to excel. I have to transfer 9 txts in total. It takes more than 20 minutes in total. This system is obviously unbearable. Then I looked for information and found that using the rang method can increase the rate. It takes only about 3-4 seconds to improve efficiency by dozens of times. The code is as follows:

 string path = "c://date//";
      StreamReader sr = new StreamReader(path);
      string strLine = ();
      int rowNum = 1;
      object missing = ;

      ApplicationClass app = new ApplicationClass();

      (true);

      Workbook book = (Workbook);
      Worksheet sheet = (Worksheet);
      Range r = sheet.get_Range("A1", "C1");

      //Get the number of rows
 
 


      object[,] objectData = new object[65535, 3]; 
      while (!(strLine))
      {
        string[] tempArr;
        tempArr = (',');
        for (int k = 1; k <= ; k++)
        {
          
          objectData[rowNum-1, k-1] = tempArr[k - 1];

        }
        strLine = ();
        rowNum++;

      }
      r = r.get_Resize(65535, 3);
      r.Value2 = objectData;
      ();
      //Save Excel file      ("D://");
      //Close the file      (false, missing, missing);
      //Exit excel      ();
      ("Conversion was successful!");