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

时间:2011-08-19 14:05:09

标签: c# excel c#-4.0 excel-2007

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

  

Microsoft.Office.Interop.Excel

只是为了澄清一下这个例子:我正在使用.txt,做一些事情,然后将其保存为.CSV(逗号分隔值)。我想打开它(按钮点击或某事......)

如何做到这一点?

5 个答案:

答案 0 :(得分:3)

配对您的评论:

  

我希望它在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();

答案 1 :(得分:2)

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

答案 2 :(得分:1)

是的,Microsoft.Office.Interop.Excel是您在Excel中打开CSV文件所需的内容。

答案 3 :(得分:1)

取决于您使用的是哪个框架(即Silverlight或Windows窗体)。 如果我是你,我将使用OpenFileDialog将逗号分隔列表中的值读入字符串或类。以下示例适用于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();
        }
    }

答案 4 :(得分:0)

这是WinForms,WPF还是ASP.NET应用程序?如果使用Office Interop库,则依赖于在该计算机上安装Office。如果它是一个Web服务器,您不希望以这种方式运行Excel。

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