我有一个数据收集程序大约需要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的是启动过程的。

您可能能够做你想做的BYB使用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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top