启动过程 – 稍后添加(MS Excel示例)

我有一个数据收集例程,需要大约10秒钟才能运行,然后将数据保存到CSV文件中:

string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Book1.csv"); StreamWriter streamWriter1 = new StreamWriter(File.Open(file, FileMode.Create, FileAccess.Write)); DataTable table = GetMyData(); // takes about 10 seconds foreach (DataRow row in table.Rows) { object[] item = row.ItemArray; for (int i = 0; i < item.Length; i++) { streamWriter1.Write(item.ToString() + ","); } streamWriter1.WriteLine(); } streamWriter1.Close(); Process.Start("Excel", "book1.csv"); 

Excel也需要一些时间来启动(5到10)。

我想修改这个技术,以便在我的数据收集之前调用Excel,以便在收集数据的时候运行应用程序,然后让数据显示文件。

考虑到这一点,这是我修改代码,但它总是告诉我文件不存在(即使它):

 Process excel = Process.Start("Excel"); if (excel != null) { string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Book1.csv"); StreamWriter streamWriter1 = new StreamWriter(File.Open(file, FileMode.Create, FileAccess.Write)); DataTable table = GetMyData(); // takes about 10 seconds foreach (DataRow row in table.Rows) { object[] item = row.ItemArray; for (int i = 0; i < item.Length; i++) { streamWriter1.Write(item.ToString() + ","); } streamWriter1.WriteLine(); } streamWriter1.Close(); for (int i = 0; i < 100; i++) { // simulate the data collection routine Thread.Sleep(100); } excel.StartInfo.Arguments = file; excel.StartInfo.ErrorDialog = true; excel.StartInfo.UseShellExecute = false; excel.StartInfo.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); try { excel.Start(); } catch (Exception err) { Console.WriteLine(err.Message); // <= Message is "The system cannot find the file specified" } } 

有什么想法吗? 我将如何正确地将文件发送到活动进程?

进程启动后,您不能指定startInfo。 StartInfo用于启动进程。

你可能可以做些什么你想要使用Process.Start()启动Excel,然后数据收集之后,使用Excel自动化来告诉Excel打开一个特定的文件。

 // connect to, or start, Excel: Excel.Application xl=new Excel.ApplicationClass(); Excel.Workbook wb = xl.Workbooks.Open(Environment.CurrentDirectory+"/SampleExcel.xls", 0, false, 5, System.Reflection.Missing.Value, System.Reflection.Missing.Value, false, System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, false, System.Reflection.Missing.Value, false, false, false);