I am trying to figure out how to create a .NET windows Forms application
that also use
Microsoft Excel. I need help simply opening and closing the workbooks.
Any help you can provide is greatly appreciated.
My end goal is to build an app to manipulate data in selected workbooks to
reformat it for data input to another application.
Right now, however I am just learning some of the basics of opening and
closing files.
What I am trying to do in the code snippets is to open an excel application,
open a selected workbook and display it in the excel window. I will also
have a windows form open.
My openFileDialog is triggered by choosing File\Open from the Windows form.
I want to load the selected workbook into the active excel application.
When I close the form I want to close the workbook and the excel
application.
// My using statement accessing Excel
using Excel = Microsoft.Office.Interop.Excel;
// These were declared at the top of the form class
internal Excel.Application xl;
internal Excel.Workbook wb;
// This code is invoked right after the standard Initialize
Components()
xl = new Excel.Application();
xl.Visible = true;
private void menuItem3_Click(object sender, System.EventArgs e)
{
// I copied this code from a standard fileOpenDialog example and tried
to alter it
Stream myStream;
// I would like to change this to open at the user's home documents
folder
openFileDialog1.InitialDirectory = @"c:\";
openFileDialog1.Filter = "Excel files (*.xls)|*.xls|All files
(*.*)|*.*" ;
openFileDialog1.FilterIndex = 1 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = openFileDialog1.OpenFile())!= null)
//I am trying to figure out how to convert the generic stream into a
workbook
// and open it in the Excel application.
{
wb = (Excel.Workbook)myStream;
xl.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet =
(Excel.Worksheet)wb.ActiveSheet;
}
}
}
private void Form1_Closed(object sender, System.EventArgs e)
{
// when I close the form I also want to close the Excel application
wb.Close();
}
Other challenges I face include
* capturing selected ranges in a workbook
* and related workbook data
* so that I can rearrange that data on a new worksheet