0

我有一个需要大约 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"
  }
}

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

4

1 回答 1

2

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

您可以通过使用 启动 Excel Process.Start(),然后收集数据后,使用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);
于 2009-08-20T16:06:11.230 回答