我已经创建了一个控制台应用程序,让它以我想要的方式运行。使用“添加项目”>在VS2010中“添加Windows窗体”选项,它自动创建了我需要的东西。我添加了一个按钮和代码来检索Excel文件(如下所示)我的问题是:
如何获取他们创建的文件并在program.cs“Main”区域中使用它?
OpenFileDialog按钮单击事件的代码,来自Form1.cs:
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...>
}
}
答案 0 :(得分:12)
System.Windows.Forms
。using System.Windows.Forms;
添加到文件的开头。[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.
}
}
}