C#實現(xiàn)把txt文本數(shù)據(jù)快速讀取到excel中
今天預(yù)實現(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)化成功!");
相關(guān)文章
ScriptControl控件執(zhí)行自定義VBS腳本示例分析
這篇文章主要介紹ScriptControl控件 msscript.ocx msscript.oca執(zhí)行自定義VBS腳本的示例代碼,需要的朋友可以參考下2013-04-04C# ListView 點擊表頭對數(shù)據(jù)進行排序功能的實現(xiàn)代碼
這篇文章主要介紹了C# ListView 點擊表頭對數(shù)據(jù)進行排序功能的實現(xiàn)代碼,需要的朋友可以參考下2017-04-04C#動態(tài)代碼生成控件后其他事件不能獲取該控件值的解決方法
這篇文章主要給大家介紹了關(guān)于C#動態(tài)代碼生成控件后其他事件不能獲取該控件值的解決方法,文中通過圖文介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-07-07