如何插入.txt到Excel?

我的.txt文件的值由空格分隔。 我想将它存储在一个Excel工作表中,每个值由空格分隔。 我想完整的第一列Excel表格填充'1',然后我的.txt的数据应分别存储在不同的列。

有人可以帮我完成代码吗?

using System; using System.Collections.Generic; using System.Text; using System.IO; using Excel = Microsoft.Office.Interop.Excel; namespace ExcelExample { class CreateExcelDoc { private Excel.Application app = null; private Excel.Workbook wb = null; private Excel.Worksheet sheet = null; private Excel.Range workSheet_range = null; public CreateExcelDoc() { createDoc(); } public void createDoc() { try { app = new Excel.Application(); app.Visible = true; wb = app.Workbooks.Add(1); sheet = (Excel.Worksheet)wb.Sheets[1]; } catch (Exception e) { Console.Write("Error"); } finally { } wb.SaveAs(@"C:\Users\AniKet\Desktop\testdata.xls"); } public void CloseExcel() { wb.Saved = true; app.Quit(); } private void btnXlsConvert_Click() { StreamReader s = new StreamReader(@"C:\Users\AniKet\Desktop\Project Work\SpatioTemporalFeature\ABHASHDEKAACTIONDistorted Mode"); string line = ""; while ((line = s.ReadLine()) != null) { string[] arr = Console.ReadLine().Split(' '); int value = arr.Length; for (int i = 0; i < value; i++) { arr } } } static void Main(string[] args) { CreateExcelDoc excell_app = new CreateExcelDoc(); excell_app.CloseExcel(); } } } 

像这样的东西应该这样做:

 private void btnXlsConvert_Click() { StreamReader s = new StreamReader( @"C:\Users\AniKet\Desktop\Project Work\SpatioTemporalFeature\blah blah"); string line = ""; int row = 1; while ((line = s.ReadLine()) != null) { sheet.Cells[row, 1].Value = 1; int col = 2; string[] arr = line.Split(' '); // this was changed int value = arr.Length; for (int i = 0; i < value; i++) { sheet.Cells[row, col++].Value = arr[i]; } row++; } } 

使用包含如下行的文本文件:

 325.762468575136 279.298876476974 4868.68544600939 1.10961923847695 8089703.163‌​96659 226.605218091523 97.6742962078548 9.71830985915493 16.943661971831 9216.419‌​6216552 62.9441248429543 87.4616147589764 

这适用于我:
对于每一行(while-loop):
1.将所有没有空格的值保存到string数组中
2.将第一列的值设置为“1”,并将文本文件中的值写入.xls文件
3.closuresstream
4.删除文件,如果它已经存在
5.保存新的.xls文件

 private void btnXlsConvert_Click() { StreamReader stream = new StreamReader(file_path); string line; int rowIndex = 1; while ((line = stream.ReadLine()) != null) { string[] values = line.Split(' '); sheet.Cells[rowIndex, 1].Value = 1; for (int columnIndex = 2; columnIndex < values.Length + 2;columnIndex++) { sheet.Cells[rowIndex, columnIndex].Value = values[columnIndex - 2]; } rowIndex++; } stream.Close(); try { if (File.Exists(@"C:\Users\Timmo\Desktop\testdata.xls")) File.Delete(@"C:\Users\Timmo\Desktop\testdata.xls"); wb.SaveAs(@"C:\Users\AniKet\Desktop\testdata.xls"); } catch(Exception ex) { MessageBox.Show(ex.Message); } }