我已经创建了一个控制台应用程序,并让它以我希望的方式工作。使用VS2010中的"Add“> "Add”选项,它自动创建了我需要的东西。我添加了一个按钮和代码来检索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;
}我希望从docPath文件中生成“program.cs”的静态主事件的那一部分
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...>
}
}发布于 2012-09-23 16:31:18
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.
}
}
}发布于 2022-05-14 20:02:11
如果使用STAThread,则不能在主函数中使用“等待”。这可以通过在STA模式下创建一个调用FolderBrowserDialog或OpenFileDialog的新线程来解决。
static void Main(string[] args)
{
Thread T = new Thread(new ThreadStart(OpenFolderBrowser));
T.SetApartmentState(ApartmentState.STA);
T.Start();
}
private static void OpenFolderBrowser()
{
using (OpenFileDialog _FolderBrowserDialog = new OpenFileDialog())
{
if (_FolderBrowserDialog.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(_FolderBrowserDialog.FileName);
}
}
}https://stackoverflow.com/questions/12553932
复制相似问题