C#在Excel中保存.csv后,我该如何打开它?

我做了一些研究,不确定是否应该使用

Microsoft.Office.Interop.Excel

只是为了澄清这个例子:我正在做一个.txt文件,然后把它保存为一个.CSV(逗号分隔值)。 我想打开它(点击button或其他…)

如何才能做到这一点?

配对您的评论:

我希望它在Excel.exe中打开。 它应该是一个单独的窗口,在我的程序完成转换后启动

只需使用System.Diagnostics.Process类来启动它:

 using System.Diagnostics.Process;//at top of your application // //At button click or after you finish editing // Process excel = new Process(); //if the excel was installed in the target machine and the default program to open csvs //then you can simply just call process start and put the file path, like: excel.Start(@"Your edited csv file path"); //otherwise: excel.StartInfo.FileName = @"The excel application file path"; excel.StartInfo.Arguments = @"Your edited csv file path"; excel.Start(); 

您可以使用文件path作为命令行参数(excel.exe C:\ myFile.csv)来启动excel进程。 这将在Excel中打开它。

是的, Microsoft.Office.Interop.Excel是您将需要在Excel中打开CSV文件。

取决于你正在使用的框架(即Silverlight或Windows窗体)。 如果我是你,我会使用OpenFileDialog从逗号分隔列表读取string或类的值。 下面的例子是silverlight。

 private void bOpenFileDialog_Click(object sender, RoutedEventArgs e) { // Create an instance of the open file dialog box. var openFileDialog1 = new OpenFileDialog(); // Set filter options and filter index. openFileDialog1.Filter = "CSV File (.csv)|*.csv|All Files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.Multiselect = false; // Call the ShowDialog method to show the dialog box. bool? userClickedOK = openFileDialog1.ShowDialog(); // Process input if the user clicked OK. if (userClickedOK == true) { // Open the selected file to read. System.IO.Stream fileStream = openFileDialog1.File.OpenRead(); using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream)) { // Read the first line from the file and write it the textbox. tbResults.Text = reader.ReadLine(); //the results of your CSV are now stored in tbResults.Text //optionally you could parse the .CSV using string.Spit(',') into a string array } fileStream.Close(); } } 

这是一个WinForms,WPF或ASP.NET应用程序吗? 如果使用Office Interop库,则依赖于正在该机器上安装的Office。 如果它是一个Web服务器,你不想以这种方式运行Excel。

查看www.SpreadSheetGear.com。 没有从属关系,只是非常满意。