今天預實現(xiàn)一功能,將txt中的數(shù)據(jù)轉(zhuǎn)到excel表中,做為matlab的數(shù)據(jù)源。搜集一些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");      //關(guān)閉文件      book.Close(false, missing, missing);      //退出excel      app.Quit();      MessageBox.Show("轉(zhuǎn)化成功!");以上代碼可以實現(xiàn)功能,由于txt中的數(shù)據(jù)有60501行,數(shù)據(jù)量太大。我估算了一下,用以上代碼轉(zhuǎn)到excel要用大約2-3分鐘。我一共要轉(zhuǎn)9個txt。一共要用20多分鐘。這樣作出系統(tǒng)顯然是讓人難以忍受的。接著找資料,發(fā)現(xiàn)用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");      //獲取行數(shù)        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");      //關(guān)閉文件      book.Close(false, missing, missing);      //退出excel      app.Quit();      MessageBox.Show("轉(zhuǎn)化成功!");新聞熱點
疑難解答
圖片精選