如何读取多个文件并写入单个.csv文件c#

时间:2017-09-18 08:46:45

标签: c#

我的意图是打开2个文件(一个.txt和一个.csv),过滤一些文本,最后将其写入单个.csv文件的一列。这是我的代码

OpenFileDialog fopen = new OpenFileDialog();
fopen.Multiselect = true;
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if (fopen.FileNames != null)
{
 //try
 //{
 Excel.Application app = new Excel.Application();
 Excel.Workbook wb = app.Workbooks.Add();
 //Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
 Excel.Worksheet sheet = wb.Sheets[1];
 Excel.Range range = sheet.UsedRange;
 int row = 1;
 int col = 1;
 foreach (string file in fopen.FileNames)
 {

 textBox1.Text = fopen.FileName;

 string save = fopen.FileName;
 string save1 = save.Split('.')[0];

 string[] text = File.ReadAllLines(file);
 for (int i = 0; i < lines; i++)
 {
    textBox2.AppendText(text[i] + "\n");
    if (text[i].Contains("<LABEL-NAME>"))
     {
        if (text[i + 1].Contains("<MAP-LABEL-NAME>"))
         {
           string split = text[i].Split('<', '>')[2];
           string split1 = text[i + 1].Split('<', '>')[2];
           textBox3.AppendText(split + "\n");
           textBox3.AppendText(split1 + "\n");
           textBox4.Text = (split + ";" + split1);
           string split2 = textBox4.Text;
           range.Cells.set_Item(row, col, split2);
           row++;
           }
           }
            if (text[i].Contains("float32"))
              {

               string split = text[i].Split('f')[1];
               textBox3.AppendText(split + "\n");
               textBox4.Text = split;

               range.Cells.set_Item(row, col, split);
               row++;

                    }
                    textBox5.Text = row.ToString();
                }

                app.DisplayAlerts = false;
                wb.SaveAs(save1 + ".csv", Excel.XlFileFormat.xlCSVWindows);
                wb.Close();       //save as
                app.Workbooks.Close();
                app.Quit();

我的问题是,代码停在

range.Cells.set_Item(row, col, split);

我尝试传递错误,但它有另一个问题,就是只将从第二个文件过滤的数据写入.csv文件。 谁能告诉我这里我做错了什么? 谢谢。

1 个答案:

答案 0 :(得分:0)

您的片段尚未完成,但您似乎在foreach循环之外打开Excel,但在结束前关闭它,因此如果您打开多个文件,它就不存在。

Excel.Application app = new Excel.Application();
.
.
foreach (string file in fopen.FileNames)
{
    //file stuff

//} foreach loop should be closed here.

            app.DisplayAlerts = false;
            wb.SaveAs(save1 + ".csv", Excel.XlFileFormat.xlCSVWindows);
            wb.Close();       //save as
            app.Workbooks.Close();
            app.Quit();
//} missing foreach closing bracket but implied

片段的其余部分缺失,但您需要在关闭Excel之前关闭foreach循环。