3

I am having a hard time figuring this out. I would like to do on button click event to open a filedialog window in which the user will select an excel file and the file will get open in excel.

I have created the filebox and I am able to get the excel to open a new file,but I can't figure out how to get the two to mesh.

what I am trying to use is as follows,

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection; 

private void button1_Click(object sender, EventArgs e)
{
   {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
           System.IO.StreamReader sr = new
           System.IO.StreamReader(openFileDialog1.FileName);
           MessageBox.Show(sr.ReadToEnd());
           sr.Close();
        }
   }
}

and I was going to use this to open excel

Excel.Application excel = new Excel.Application();
Excel.Workbook wb = excel.Workbooks.Open(filename);

2 Answers 2

4

You should declare excel and wb as fields of your form. Something like

partial class MyForm : Form
{
  private Excel.Application _excel;
  private Excel.Workbook _wb;
  // and so on
}

Then you should replace

System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);
MessageBox.Show(sr.ReadToEnd());
sr.Close();

with

_excel = new Excel.Application();
_wb = _excel.Workbooks.Open(openFileDialog1.FileName);
Sign up to request clarification or add additional context in comments.

10 Comments

Why? Is it because his excel and wb objects drop out of scope?
Yep. If you declare them inside the event handler they are out of scope as soon as you leave the handler.
i get "An object reference is required for the non-static field, method, or property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object, object, object, object, object, object, object, object, object, object, object, object, object, object)'
There were two nasty typos in the last piece of code of my answer. Maybe that's causing the error.
there are no errors now. However nothing happens when selecting the file
|
4

Just pass the filename from the open file dialog to the Excel application.

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection; 

private void button1_Click(object sender, EventArgs e)
{
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            Excel.Application excel = new Excel.Application();
            Excel.Workbook wb = excel.Workbooks.Open(openFileDialog1.FileName);

1 Comment

all that happens when i run this code is the form freezes for 5-10 sec and then nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.