Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#(列)将多个CSV文件导入Excel_C#_Excel_Csv - Fatal编程技术网

使用C#(列)将多个CSV文件导入Excel

使用C#(列)将多个CSV文件导入Excel,c#,excel,csv,C#,Excel,Csv,C#使用Visual Studio 2017社区。这是一个WinFormsApp 为清晰起见进行编辑:我的目标是创建一个Excel电子表格,其中包含从文本文件中提取的数据。在这种情况下,文本文件是RPT文件(来自测量系统的报告文件)。我当前的代码可以工作,但只完成了一半。它当前所做的是从给定目录中获取所有单个RPT文件,并为每个文件创建单个CSV文件 所以现在,我不确定该走哪条路:要么重写当前代码直接输出到Excel,要么添加到当前代码将CSV文件导入Excel。不管怎样,我需要一些帮助 我当前

C#使用Visual Studio 2017社区。这是一个WinFormsApp

为清晰起见进行编辑:我的目标是创建一个Excel电子表格,其中包含从文本文件中提取的数据。在这种情况下,文本文件是RPT文件(来自测量系统的报告文件)。我当前的代码可以工作,但只完成了一半。它当前所做的是从给定目录中获取所有单个RPT文件,并为每个文件创建单个CSV文件

所以现在,我不确定该走哪条路:要么重写当前代码直接输出到Excel,要么添加到当前代码将CSV文件导入Excel。不管怎样,我需要一些帮助

我当前的代码是有效的,它接受每个文本文件(一个报告文件,RPT文件)并创建一个相应的CSV文件。我想知道一开始这样做是否走错了路

    private void button1_Click(object sender, EventArgs e)
    {
        string dir;
        string serialNumber;
        //string infile;
        string outfile;
        string featureName;
        string result;

        // Prompt the user to navigate to and select a directory where RPT files reside
        FolderBrowserDialog folderDlg = new FolderBrowserDialog();
        folderDlg.ShowNewFolderButton = true;
        // Show the FolderBrowserDialog.
        DialogResult folder = folderDlg.ShowDialog();
        if (folder == DialogResult.OK)
        {
            // dir is the full path to the file, excluding the filename
            dir = folderDlg.SelectedPath;
            fileNameTextBox.Text = folderDlg.SelectedPath;
            Environment.SpecialFolder root = folderDlg.RootFolder;

            // Get all the RPT files in the specified directory; do NOT look through sub-directories
            //string[] Files = Directory.GetFiles(dir, "*.RPT", SearchOption.TopDirectoryOnly);

            foreach (string filename in Directory.GetFiles(dir, "*.RPT", SearchOption.TopDirectoryOnly))
            {
                // serialnumber is the filename WITHOUT the extension and WITHOUT the path to the file included.
                serialNumber = Path.GetFileNameWithoutExtension(filename);

                // Create an output CSV file for each serial number; put in same directory as RPT files.
                outfile = dir + "\\" + serialNumber + ".CSV";
                //}

                var lines = File.ReadAllLines(filename);
                var csv = new StringBuilder();

                // In first row of every file, put serial number
                var topLine = string.Format("{0},{1}", "", serialNumber);
                csv.AppendLine(topLine);

                for (int i = 0; i < lines.Length; i++)
                {
                    // Lines containg the string "---" are result lines.  The data we need is in this line.
                    //if (lines[i].Contains("  ---") || lines[i].Contains("+--"))  
                    if (lines[i].Contains("---"))
                    {
                        // The first feature of each page needs special treatment, because that's where the header is.
                        // "Actual   Nominal  Difference  ... etc.," which appears at the top of every RPT file page.
                        // and because -- in these cases -- the  Feature Name is not directly above the result line.
                        //
                        // So, check the line directly above the result line for the length of the line.
                        // If the length of this line > 50, we know that it's the header line.
                        // In these cases, the featureName is one row above the header line.
                        //if (lines[i-1].Length > 50)

                        // Let's try a different method to identify first feature on each page.
                        // Instead of looking at Length of line, let's look at the entire string
                        // to see if the substring "Actual   Nominal" is in the line
                        // If it is, we've found the first feature of a page.
                        if (lines[i - 1].Contains("Actual   Nominal"))
                        {
                            featureName = lines[i - 2].Trim().ToString();
                            featureNameTextBox.Text = featureName;
                            result = lines[i].Substring(12, 10).Trim().ToString();
                            resultTextBox.Text = result;
                            var newLine = string.Format("{0},{1}", featureName, result);
                            csv.AppendLine(newLine);
                        }
                        else
                        {
                            featureName = lines[i - 1].Trim().ToString();
                            featureNameTextBox.Text = featureName;
                            result = lines[i].Substring(12, 10).Trim().ToString();
                            resultTextBox.Text = result;
                            var newLine = string.Format("{0},{1}", featureName, result);
                            csv.AppendLine(newLine);
                        }
                    }
                }
                //Once outside loop, write to file
                File.WriteAllText(outfile, csv.ToString());
            }
        }

    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}
private void按钮1\u单击(对象发送者,事件参数e)
{
字符串目录;
字符串序列号;
//字符串填充;
排管器;
字符串特征名;
字符串结果;
//提示用户导航到并选择RPT文件所在的目录
FolderBrowserDialog folderDlg=新建FolderBrowserDialog();
folderDlg.ShowNewFolderButton=true;
//显示FolderBrowser对话框。
DialogResult folder=folderDlg.ShowDialog();
如果(文件夹==DialogResult.OK)
{
//dir是文件的完整路径,不包括文件名
dir=folderDlg.SelectedPath;
fileNameTextBox.Text=folderDlg.SelectedPath;
Environment.SpecialFolder root=folderDlg.RootFolder;
//获取指定目录中的所有RPT文件;不要查看子目录
//string[]Files=Directory.GetFiles(dir,“*.RPT”,SearchOption.TopDirectoryOnly);
foreach(Directory.GetFiles(dir,*.RPT,SearchOption.TopDirectoryOnly)中的字符串文件名)
{
//serialnumber是不带扩展名且不包含文件路径的文件名。
serialNumber=Path.GetFileNameWithoutExtension(文件名);
//为每个序列号创建一个输出CSV文件;与RPT文件放在同一目录中。
outfile=dir+“\\”+serialNumber+“.CSV”;
//}
var lines=File.ReadAllLines(文件名);
var csv=新的StringBuilder();
//在每个文件的第一行,输入序列号
var topLine=string.Format(“{0},{1},”,serialNumber);
csv.AppendLine(背线);
对于(int i=0;i50,我们知道这是标题行。
//在这些情况下,featureName位于标题行上方一行。
//if(行[i-1]。长度>50)
//让我们尝试不同的方法来识别每个页面上的第一个功能。
//我们来看看整个字符串,而不是看行的长度
//查看子字符串“实际标称”是否在该行中
//如果是,我们已经找到了页面的第一个功能。
如果(第[i-1]行包含(“实际标称”))
{
featureName=lines[i-2].Trim().ToString();
featureNameTextBox.Text=featureName;
结果=行[i]。子字符串(12,10)。Trim()。ToString();
resultTextBox.Text=结果;
var newLine=string.Format(“{0},{1}”,featureName,result);
csv.AppendLine(换行符);
}
其他的
{
featureName=lines[i-1].Trim().ToString();
featureNameTextBox.Text=featureName;
结果=行[i]。子字符串(12,10)。Trim()。ToString();
resultTextBox.Text=结果;
var newLine=string.Format(“{0},{1}”,featureName,result);
csv.AppendLine(换行符);
}
}
}
//一旦超出循环,写入文件
File.WriteAllText(outfile,csv.ToString());
}
}
}
私有无效退出按钮单击(对象发送者,事件参数e)
{
这个。关闭();
}
}
}

我想创建一个Excel电子表格,其中前两列是CSV文件中显示的前两列,Excel工作表中的后续列是仅来自当前CSV文件的第二列。我想直接从RPT文件转到Excel,但我不确定这是不是一种更简单的方法

下面是一些截图,可以更好地解释问题


不清楚输入文件是CSV还是“简单文本文件”,但无论如何,你都不能先读取第一个文件,然后再合并吗