8

コンソール アプリケーションを作成し、希望どおりに動作させました。VS2010 で [アイテムの追加] > [Windows フォームの追加] オプションを使用すると、必要なものが自動的に作成されました。Excel ファイルを取得するためのボタンとコードを追加しました (以下)。私の質問は次のとおりです。

彼らが作成したファイルを取得して、私のprogram.csの「メイン」エリアで使用するにはどうすればよいですか?

Form1.cs からの OpenFileDialog ボタン クリック イベントのコード:

private void btnSelect_Click(object sender, EventArgs e)
{
OFD.openFileDialog OFD = new OpenFileDialog();
OFD.Multiselect = false;
OFD.Title = "Open Excel Document";
OFD.Filter = "Excel Document|*.xlsx;*.xls";
OFD.ShowDialog();
string docPath = OFD.FileName;
}

program.cs ファイルから「docPath」を作成したい静的メイン イベントのその部分

static void Main(string[] args)
    {
        var excel = new ExcelQueryFactory();
        excel.FileName = @"C:\Users\Christopher\Desktop\BookData\TestResults.xls";
       <...code executed on opened excel file...>
     }

お時間をいただきありがとうございます。

これは私の完成したソリューションです:

class Program
{
    [STAThread]
    static void Main(string[] args)
    {

        var excel = new ExcelQueryFactory();
        OpenFileDialog OFD = new OpenFileDialog();
        OFD.Multiselect = false;
        OFD.Title = "Open Excel Document";
        OFD.Filter = "Excel Document|*.xlsx;*.xls";
        OFD.ShowDialog();
        string filePath = OFD.FileName;
        excel.FileName= filePath.ToString();
        <.the rest of my program is below...>
    }  
}
4

1 に答える 1

17
  1. コンソールアプリケーションを右クリックし、参照を追加しますSystem.Windows.Forms
  2. using System.Windows.Forms;ファイルの先頭に追加します。
  3. [STAThread]属性をに追加してMain、ファイルを開くダイアログと互換性を持たせます。

[STAThread]
public static void Main(string[] args)
{
    var dialog = new OpenFileDialog
                     {
                         Multiselect = false,
                         Title = "Open Excel Document",
                         Filter = "Excel Document|*.xlsx;*.xls"
                     };
    using (dialog)
    {
        if (dialog.ShowDialog() == DialogResult.OK)
        {
            var excel = new ExcelQueryFactory { FileName = dialog.FileName };
            // code executed on opened excel file goes here.
        }
    }
}
于 2012-09-23T16:31:18.103 に答える