C#实现把txt文本数据快速读取到excel中_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C#实现把txt文本数据快速读取到excel中

发布时间:2026-01-18  |  点击率:

今天预实现一功能,将txt中的数据转到excel表中,做为matlab的数据源。搜集一些c#操作excel的程序。步骤如下:

下载一个Microsoft.Office.Interop.Excel.dll   在项目中引用。

编写代码如下:

      string path = "c://date//xyu.txt";
      StreamReader sr = new StreamReader(path);
      string strLine = sr.ReadLine();
      int rowNum = 1;
      object missing = System.Reflection.Missing.Value;

      ApplicationClass app = new ApplicationClass();

      app.Application.Workbooks.Add(true);

      Workbook book = (Workbook)app.ActiveWorkbook;
      Worksheet sheet = (Worksheet)book.ActiveSheet;
      while (!string.IsNullOrEmpty(strLine))
      {
        string[] tempArr;
        tempArr = strLine.Split(',');
        for (int k = 1; k <= tempArr.Length; k++)
        {
          sheet.Cells[rowNum, k] = tempArr[k - 1];

        }
        strLine = sr.ReadLine();
        rowNum++;

      }

      //保存excel文件
      book.SaveCopyAs("D://source.xls");
      //关闭文件
      book.Close(false, missing, missing);
      //退出excel
      app.Quit();
      MessageBox.Show("转化成功!");

  以上代码可以实现功能,由于txt中的数据有60501行,数据量太大。我估算了一下,用以上代码转到excel要用大约2-3分钟。我一共要转9个txt。一共要用20多分钟。这样作出系统显然是让人难以忍受的。接着找资料,发现用rang方法可以提高速率。只用大约3-4秒钟的时间,提高效率几十倍。代码如下:

 string path = "c://date//xyu.txt";
      StreamReader sr = new StreamReader(path);
      string strLine = sr.ReadLine();
      int rowNum = 1;
      object missing = System.Reflection.Missing.Value;

      ApplicationClass app = new ApplicationClass();

      app.Application.Workbooks.Add(true);

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

      //获取行数

 
 


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

        }
        strLine = sr.ReadLine();
        rowNum++;

      }
      r = r.get_Resize(65535, 3);
      r.Value2 = objectData;
      r.EntireColumn.AutoFit();
      //保存excel文件
      book.SaveCopyAs("D://source.xls");
      //关闭文件
      book.Close(false, missing, missing);
      //退出excel
      app.Quit();
      MessageBox.Show("转化成功!");

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598