首页 > 解决方案 > 使用 C# 将多个 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();
    }
}

}

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

这里有一些屏幕截图可以更好地解释事情。

https://imgur.com/a/SlomzVw

标签: c#excelcsv

解决方案


推荐阅读