Импорт нескольких файлов CSV в Excel с C # (столбцы) - PullRequest
1 голос
/ 29 сентября 2019

C # с использованием Visual Studio 2017 Community. Это 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...