启动流程 - 然后稍后添加(MS Excel示例)

时间:2009-08-20 14:53:26

标签: excel arguments process.start

我有一个数据收集例程需要大约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"
  }
}

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

1 个答案:

答案 0 :(得分:2)

启动进程后,无法指定startInfo。 StartInfo用于启动该过程。

您可以使用Process.Start()启动Excel,然后在数据收集后使用,使用Excel automation告诉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);