簡體   English   中英

C# - 從C#WinForm應用程序運行/執行“Excel到CSV文件轉換器”控制台應用程序

[英]C# - Running / Executing “Excel to CSV File Converter” Console App from C# WinForm App

我正在使用帶有OpenFileDialog,FileBrowserDialog的C#開發WinForms應用程序,並且我已經啟用了我想要的多個xls文件的選擇:

  1. 將所選文件復制到Consolidated目錄
  2. 通過命令提示符命令[C:\\ CommissionRecon \\ ConvertExcel \\ ConvertExcelTo.exe ^ xxxxx.xls ^ xxxx.csv]將所選文件轉換為.csv文件
  3. 使用命令提示符將所有.csv文件合並到1個csv文件中[.csv文件位置:復制* .csv ^ filename.csv]

執行此控制台應用程序的語法是什么?

請檢查下面的代碼並推薦一些修復程序。 我包含了很多代碼,以便您可以獲得全局,但我主要是希望您在可能的情況下查看私有void sourceFiles_Click方法。

謝謝!

這是MainForm.CS文件中的代碼:

    // Select Source Files Button 
    private void sourceFiles_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
        this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
        this.sourceFileOpenFileDialog.FilterIndex = 2;
        this.sourceFileOpenFileDialog.RestoreDirectory = true;
        this.sourceFileOpenFileDialog.Multiselect = true;
        this.sourceFileOpenFileDialog.Title = "Excel File Browser";

        DialogResult dr = this.sourceFileOpenFileDialog.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            string consolidatedFolder = targetFolderBrowserDialog.SelectedPath; 
            // Read the files
            foreach (String file in sourceFileOpenFileDialog.FileNames)
            {
                try
                {
                    // Copy each selected xlsx files into the specified TargetFolder 

                    System.IO.File.Copy(fileName, consolidatedFolder + @"\" + System.IO.Path.GetFileName(fileName)); 

                    // Convert each selected XLSX File to CSV Using the command prompt
                    // [I:\CommissisionReconciliation\App\ConvertExcel\ConvertExcelTo.exe ^ .XLS file location ^ filename.csv] 
                    // example: ConvertExcelTo.exe ^ I:\CommissisionReconciliation\ Review\_Consolidated\ALH\2011-350-00-600070-
                    // 03-09alh-AMLHS of Florida.xlsx ^ 2011-350-00-600070-03-09alh-AMLHS of Florida.csv

                    Process covertFilesProcess = new Process();

                    covertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
                    covertFilesProcess.StartInfo.FileName = sourceFileOpenFileDialog.FileName; 
                    covertFilesProcess.StartInfo.Arguments = "ConvertExcelTo.exe" + " ^ " + targetFolderBrowserDialog.SelectedPath + "^" + sourceFileOpenFileDialog.FileName + ".csv";
                    covertFilesProcess.StartInfo.UseShellExecute = false;
                    covertFilesProcess.StartInfo.CreateNoWindow = true;
                    covertFilesProcess.StartInfo.RedirectStandardOutput = true;
                    covertFilesProcess.StartInfo.RedirectStandardError = true;
                    covertFilesProcess.Start();

                    StreamReader sOut = covertFilesProcess.StandardOutput;
                    StreamReader sErr = covertFilesProcess.StandardError;

                }

                catch (SecurityException ex)
                {
                    // The user lacks appropriate permissions to read files, discover paths, etc.
                    MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
                    "Error message: " + ex.Message + "\n\n" +);
                }
                catch (Exception ex)
                {
                    // Could not load the image - probably related to Windows file system permissions.
                    MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                     + ". You may not have permission to read the file, or " +
                     "it may be corrupt.\n\nReported error: " + ex.Message);
                }

                finally
                {
                    sOut.Close();
                    sErr.Close();
                }

                try
                {
                    // Combine all .csv files into 1 csv file using the command prompt
                    // [.csv File location: Copy *.csv ^ filename.csv]
                    // example: [.CSV I:\CommissisionReconciliation\ Review\_Consolidated\ALH\: Copy *.csv 
                    // ^2011-350-00-600070-03-09alh-AMLHS of Florida.csv)

                    Process consolidateFilesProcess = new Process();

                    // substring function to take off the extension from sourceFileOpenFileDialog.FileName
                    // int csvFileName.Length = sourceFileOpenFileDialog.FileName.Length - 3;  

                    consolidateFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
                    consolidateFilesProcess.StartInfo.FileName = sourceFileOpenFileDialog.FileName; 
                    consolidateFilesProcess.StartInfo.Arguments = ".CSV " + " ^ " + targetFolderBrowserDialog.SelectedPath + ": Copy *.csv ^" + csvFileName+ ".csv";
                    consolidateFilesProcess.StartInfo.UseShellExecute = false;
                    consolidateFilesProcess.StartInfo.CreateNoWindow = true;
                    consolidateFilesProcess.StartInfo.RedirectStandardOutput = true;
                    consolidateFilesProcess.StartInfo.RedirectStandardError = true;
                    consolidateFilesProcess.Start();

                    StreamReader sOut = consolidateFilesProcess.StandardOutput;
                    StreamReader sErr = consolidateFilesProcess.StandardError;
                }

                catch (SecurityException ex)
                {
                    // The user lacks appropriate permissions to read files, discover paths, etc.
                    MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
                    "Error message: " + ex.Message + "\n\n" +);
                }
                catch (Exception ex)
                {
                    // Could not load the image - probably related to Windows file system permissions.
                    MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                     + ". You may not have permission to read the file, or " +
                     "it may be corrupt.\n\nReported error: " + ex.Message);
                }

                finally
                {
                    sOut.Close();
                    sErr.Close();
                }

            } // ends foreach (String file in openFileDialog1.FileNames)
        }  // ends if (dr == System.Windows.Forms.DialogResult.OK)
    } // ends selectFilesButton_Click method 

        if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        textBoxSourceFiles.Text = sourceFileOpenFileDialog.FileNames;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }

        if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            Log("Source Files: " + sourceFileOpenFileDialog.SelectedFiles);
        }
        textBoxSourceFiles.Text = sourceFileOpenFileDialog.SelectedFiles;
    }

創建ProcessSTartInfo時,需要指定要作為文件名運行的進程的可執行文件!

例如:

Process covertFilesProcess = new Process();

covertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
covertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";
covertFilesProcess.StartInfo.Arguments = "^ " + targetFolderBrowserDialog.SelectedPath + "^" + sourceFileOpenFileDialog.FileName + ".csv";
covertFilesProcess.StartInfo.UseShellExecute = true;
covertFilesProcess.StartInfo.CreateNoWindow = true;
covertFilesProcess.StartInfo.RedirectStandardOutput = true;
covertFilesProcess.StartInfo.RedirectStandardError = true;
covertFilesProcess.Start();

StreamReader sOut = covertFilesProcess.StandardOutput;
StreamReader sErr = covertFilesProcess.StandardError;

首先要做的事情:

try
{
    ...
    StreamReader sOut = covertFilesProcess.StandardOutput;
}
sOut.close();

sOut在try塊中聲明 - 它在外面不可見。 你需要將它移到外面

StreamReader sOut = null;
try
{
    ...
    sOut = covertFilesProcess.StandardOutput;
}

if (sOut != null) sOut.Close();

與sErr相同

更新 :對於SecurityException,您需要使用System.Security添加,而對於您需要使用System.Diagnostics添加的Process。 並且未聲明變量fileName - 因此編譯器不知道它是什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM