简体   繁体   中英

Open Excel File using OpenFileDialog in C# Windows Form

I am able to choose an Excel file, but after I clicked on Open, the excel file doesn't appear. What should I do? I'm still new with OpenFileDialog, it will be good if anyone can tell what I should add to make the excel file appear after clicking on Open.

Modified from http://www.c-sharpcorner.com/uploadfile/mahesh/openfiledialog-in-c-sharp/

This is my code:

private void BrowseButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = @"C:\";
        openFileDialog1.Title = "Browse Text Files";

        openFileDialog1.CheckFileExists = true;
        openFileDialog1.CheckPathExists = true;

        openFileDialog1.DefaultExt = "txt";
        openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        openFileDialog1.ReadOnlyChecked = true;
        openFileDialog1.ShowReadOnly = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
                string text = File.ReadAllText(file);
                int size = text.Length;
            }
            catch (IOException)
            {
            }

        }
    }


public bool ThumbnailCallback()
   {
     return false;
   }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {

    }

After I clicked Open, only the file name appear, but not the excel file - https://i.stack.imgur.com/GXToy.jpg

You need to set the filter to select excel files.

openFileDialog1.Filter = "Excel Worksheets|*.xls";

You can refer the documentation here .

If you only want to open the Excel file using the default application that is associated to *.xlsx files (which usually is MS Excel when it is installed), then you can simply use the Process.Start(string) method . In you case it may look something like this:

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        Process.Start(openFileDialog1.FileName);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM