Click here to Skip to main content
Click here to Skip to main content

An introduction on how to control Excel 2003 with J# .NET

By , 14 Nov 2004
 

Sample Image - JExcel.jpg

Introduction

In this article, we will be focusing on how to control Microsoft Excel 2003 with the J# language through COM automation. We will be targeting the version 1.1 of the .NET framework (Visual Studio 2003).

Open Visual Studio and select a new J# Windows Application.

Add a reference to "Microsoft Excel 11.0 Object Library".

Add a Button, and a PictureBox Win form control to the application. Click the Button twice to implement a button handler.

The application instance

The most important classes are the application, workbook, worksheet and range classes. The application class represents the Excel application with workbooks. Workbooks have worksheets with cells. Cells can be represented by ranges.

To open an instance of Excel, type:

    Microsoft.Office.Interop.Excel.ApplicationClass excel =
       new Microsoft.Office.Interop.Excel.ApplicationClass();

This will not show Excel on the desktop, but run it in the background. If you want to make it visible on the desktop, set the following property to true. There are no differences other that Excel will be visible on the desktop. This can be useful while debugging.

excel.set_Visible( true );

If you want to exit Excel, type:

excel.Quit();

One very important property that will make your system run faster is to disable the screen updating while you do operations. It is very important that you enable the screen updating when you are done. Excel will not do this for you. Remember to switch on the screen updating in your code where it will run, regardless of exceptions.

    try 
    {
        excel.set_ScreenUpdating( false );
        // ... do excel operations here
    } 
    finally
    {
        excel.set_ScreenUpdating( true );
    }

Another very important property is the alert property. This property controls if Excel should display warning dialogs or not, like the 'Save as' dialog if you forget to save the workbook before quitting Excel. Just like the screen updating property, the alert property will not reset this property for you when you are done.

    try 
    {
        excel.set_DisplayAlerts( false );
        // do excel operations here...
    }
    finally
    {
        excel.set_DisplayAlerts( true );
    }

Excel has several other display properties you may want to take a look at. In the Visual Studio IDE, type excel.set_D to show all the properties.

If you want your users to be able to edit the workbooks, do the following command:

    excel.set_UserControl( true );

The workbook

As you probably have found out, you can not do much work without a workbook. The workbook collection enables you to open new work books, save work books, and other important operations.

Open a new workbook

To open a new workbook, do the following:

    Microsoft.Office.Interop.Excel.Workbook workbook = 
        excel.get_Workbooks().Add(System.Reflection.Missing.Value );

Close a workbook

When you want to close a workbook, type:

    workbook.Close( 
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value, 
        System.Reflection.Missing.Value );

This will assume you do not want to save any changes to the workbook. If you did any changes to the workbook, you can close it and save any changes with this command:

    workbook.Close( (System.Boolean)true, "C:\\test.xls", 
        System.Type.Missing );

Please notice the .NET boxing of the Java boolean type. The second argument is the filename.

Save, SaveAs and SaveCopyAs

To save the workbook, simply call:

    workbook.Save();

A more advanced save call is the SaveAs. This call enables you to specify a filename and path, file format, password, file access mode, and more. This example will save the workbook in the C:\test.xls as an Excel format with no password.

    workbook.SaveAs( "c:\\test.xls",
        Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value,
        System.Reflection.Missing.Value );

If you want to save a copy without changing the name of the workbook instance, simply do a SaveCopyAs call:

workbook.SaveCopyAs( "c:\\copy.xls" );

Printing a workbook

We have two useful methods for printing, preview and print. The preview method will show a window on what the paper will look like. The print method will print the specified pages in the workbook on a printer.

The preview method is as follows. Please notice the .NET boxing of the Java boolean.

    workbook.PrintPreview( (System.Boolean)false );

If you want to print the workbook:

    workbook.PrintOut( From page, To page, Copies, Preview, 
        ActivePrinter, PrintToFile, Collate, PrToFilename );

Calculate the workbook

Sometimes it is useful to calculate all workbooks in one command. That can be done with the following command:

    excel.Calculate();

The worksheet

The worksheets contain cells and are inside the workbook. You get a reference to the active worksheet with the get_Activesheet() command.

    Microsoft.Office.Interop.Excel.Worksheet sheet =
        excel.get_ActiveSheet();

Fill data in the cells

There are many ways to fill in the cells in a worksheet. One way is to use a two dimensional array.

Example one:

To fill in the numbers 1 to 10 in A1 to J1, do the following:

        int values[,] = new int[1,10];
        values[0,0] = 1;
        values[0,1] = 2;
        values[0,2] = 3;
        values[0,3] = 4;
        values[0,4] = 5;
        values[0,5] = 6;
        values[0,6] = 7;
        values[0,7] = 8;
        values[0,8] = 9;
        values[0,9] = 10;
        sheet.get_Range("A1", "J1").set_Value2( values );

Example two:

The code will look like this:

        int values[,] = new int[10,1];
        values[0,0] = 1;
        values[1,0] = 2;
        values[2,0] = 3;
        values[3,0] = 4;
        values[4,0] = 5;
        values[5,0] = 6;
        values[6,0] = 7;
        values[7,0] = 8;
        values[8,0] = 9;
        values[9,0] = 10;
        sheet.get_Range("A1", "A10").set_Value2( values );

Example three:

We will, in this example, make a 10 x 10 worksheet with a text headline and a 10x9 random integer array.

        String headline[,] = new String[1,10];
        headline[0,0] = new String("Dave");
        headline[0,1] = new String("Tom");
        headline[0,2] = new String("Thomas");
        headline[0,3] = new String("Michael");
        headline[0,4] = new String("Bob");
        headline[0,5] = new String("John");
        headline[0,6] = new String("Peter");
        headline[0,7] = new String("Lars");
        headline[0,8] = new String("Jay");
        headline[0,9] = new String("Brian");
        sheet.get_Range("A1", "J10").set_Value2( headline );

        int value[,] = new int[9,10];
        System.Random random = new System.Random( );
        for( int counterA = 0; counterA < 9 ; counterA++ )
            for( int counterB = 0; counterB < 10; counterB++ )
                value[counterA, counterB] = random.Next(100);
        sheet.get_Range("A2", "J10").set_Value2( value );

Formulas

This example will add all numbers from A2 to A10 (B2 to B10, C2 to C10 and so on), and store the result in A11 (B11, C11 and so on) with bold text.

    Microsoft.Office.Interop.Excel.Font font = 
            sheet.get_Range("A11", "J11").get_Font();
    font.set_Bold( (System.Boolean)true );
    sheet.get_Range("A11", "J11").set_Formula("=SUM(A2..A10)");

Charts

Charts are useful for showing information graphically. To open a new chart, do:

    Microsoft.Office.Interop.Excel.Chart chart = 
        (Microsoft.Office.Interop.Excel.Chart)excel.get_Charts().Add( 
            System.Reflection.Missing.Value, 
            System.Reflection.Missing.Value, 
            System.Reflection.Missing.Value, 
            System.Reflection.Missing.Value );


    chart.ChartWizard( sheet.get_Range("A1", "J10"), 

    Microsoft.Office.Interop.Excel.XlChartType.xl3DColumn, 
        System.Reflection.Missing.Value, 
        Microsoft.Office.Interop.Excel.XlRowCol.xlRows, 
        System.Reflection.Missing.Value, 
        System.Reflection.Missing.Value, 
        System.Reflection.Missing.Value, 
        "Sales", 
        "Employee", 
        "Export in percent", 
        System.Reflection.Missing.Value );

Move the chart into the sheet with:

chart.Location(
  Microsoft.Office.Interop.Excel.XlChartLocation.xlLocationAsObject, 
              sheet.get_Name() );

To move the chart on the sheet, do:

    sheet.get_Shapes().Item("Chart 1").set_Left( 2.10f );
    sheet.get_Shapes().Item("Chart 1").set_Top( 150.0f );

Resize the chart with:

    sheet.get_Shapes().Item("Chart 1").set_Width( 500.0f );
    sheet.get_Shapes().Item("Chart 1").set_Height( 300.0f );

One interesting method is the CopyPicture(). This method allows you to copy anything from a sheet and store it on the clipboard, e.g., as a bitmap. This bitmap can be copied into any J# project for further processing and conversions.

    sheet.get_Shapes().Item("Chart 1").CopyPicture(
        Microsoft.Office.Interop.Excel.XlPictureAppearance.xlScreen,
        Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap );

If you add a PictureBox control to your application, you can paste the chart into the J# application with the following code:

    System.Drawing.Bitmap bitmap =  new System.Drawing.Bitmap( 
        (System.Drawing.Image)Clipboard.GetDataObject().GetData(
        System.Windows.Forms.DataFormats.Bitmap ));
    this.pictureBox1.set_Image( bitmap );

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Lars-Inge Tønnessen
Web Developer
Norway Norway
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhow to set my series value?memberykt_temp15 Nov '06 - 18:10 
by default, its values are "Series 1, Series 2...", that's not useful...
QuestionExcel and ChartmemberPeter N Johnson10 Aug '06 - 13:02 
This is a great example of how to use excel through interop, it documents all of my own personal findings and shows you also discovered similar issues.
 
One issue I am having trouble overcoming is this
 
You have three columns A, B, C and you want to create a chart based on columns A and C.
 
How do you go about setting a charts data source to be the columns A, and C without including column B?
 
i tried using the following code.
 


keyColumn = "A1:A20";
selectedCellRange = "C1:C20";
 
Excel.Range data = sheet.get_Range(keyColumn, selectedCellRange);

// Setup the chart and set the data to use.
chart.ChartWizard(data,
XlChartType.xlCylinderColClustered,
Missing.Value,
Excel.XlRowCol.xlColumns,
Missing.Value,
Missing.Value,
Missing.Value,
title,
xAxisLabel,
yAxisLabel,
Missing.Value);

 
however this always throws an exception, with a non too helpful COM exception code.
 
I have also tried specifying the range as excel does "A1:A20,C1:C20" then passing in Missing.Value into the second part of the get_range method. This produces the same exception.
 
Could you provide me with any feedback? When I'm doing any excel work i always create excel macros and copy them but in this instance this method has failed me Dead | X|
 
Many Thanks
 
Pete
GeneralCheckBox in Excel Sheetmemberanisdilou18 May '06 - 4:42 
Hi,
I have checkboxes in an excel sheet, I want to read them values in .NET environement with Microsoft Excel 11.0 Object Library (namespace Microsoft.Office.Interop.Excel). Please can you help me.
Thank you.
GeneralVisual Studio 2000memberxjli25 Apr '06 - 7:24 
Thanks for great article.
I tried to use them with Office Object 11.0 and Visual Studio 2000, the ".get_Workbooks().Open()" method doesn't work.
Any idea?
GeneralUnable to read back values for two dimentional arraymemberRavi1232 Mar '06 - 10:40 
I am trying to read back the values already written to a worksheet, using a two dimensional array.
I have the code as this:

..........
double Ravdble[,] = new double[10,1];
double RavdbleTEST[,] = new double[10,1];
Ravdble[0,0] = 10.5;
Ravdble[1,0] = 10.1;
Ravdble[2,0] = 8;
Ravdble[3,0] = 7;
Ravdble[4,0] = 6;
Ravdble[5,0] = 5;
Ravdble[6,0] = 4;
Ravdble[7,0] = 3;
Ravdble[8,0] = 2;
Ravdble[9,0] = 1;
sheet.get_Range("C5", "C14").set_Value2( Ravdble );//public abstract void set_Value2 ( Object ) Member of Microsoft.Office.Interop.Excel.Range
 
RavdbleTEST = (double[,])(sheet.get_Range("C5", "C14").get_Value2());
It gives and error saying that "Specified cast is not valid".
Please advise as to what I am doing wrong here.
Thanks,

 
RaviM
GeneralOld format or invalid type library errormemberelterra9 Apr '05 - 0:03 
Hi. Greate article for excel basics . But however I couldn't
run sources. There is a error "Old format or invalid type library" when i trying to add workbook. I have Office 2003 XP Proffessional(SP1) and Excel Primary Interop assemly installed. I also tried to register PIA again but it doesn't help. Do you have any ideas what problem is ?
GeneralRe: Old format or invalid type library errormemberHamilton Verissimo13 Jul '05 - 6:34 
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369
 

--
Cheers,
hammett
http://www.castleproject.org/~hammett

GeneralRe: Old format or invalid type library errormemberfractl13 Sep '06 - 5:11 
I found the solution here - creating your own XLLEX.dll from excel.exe - worked a treat. Smile | :)
http://blogs.msdn.com/eric_carter/archive/2005/06/15/429515.aspx[]
 
Julie
GeneralRe: Old format or invalid type library errormemberMartinSchmidt24 Oct '07 - 23:01 
The workaround proposed in http://support.microsoft.com/kb/320369/EN-US/ (temporarily set the thread locale to en-US) works very well for me though.
GeneralRe: Old format or invalid type library errormemberrejean_perron@yahoo.ca10 Jan '07 - 9:58 
See microsoft bug kb article 320369: http://support.microsoft.com/kb/320369
Generalexcel.get_Workbooks() method doesn't existmemberAshley van Gerven5 Mar '05 - 20:17 
Hi,
 
I was very pleased to come accross your article, however using the steps you've outlined I experience a problem with the part "excel.get_Workbooks()". According to the Object Browser there is no such method in Excel.ApplicationClass. I have Office 2003 Basic Edition installed, and have referenced the correct ddls (i.e. office 11).
 
Do you have any ideas why this might be happening?
Generalfigured it out...memberAshley van Gerven5 Mar '05 - 21:19 
I just realized the "get_" method is java's way of accessing the Workbooks property. So it's all good... thanks for the handy article!
GeneralRe: excel.get_Workbooks() method doesn't existmemberKarthikaG17 Jun '05 - 1:12 
I also encountered the same problem..see the following code..
I hope that would be useful
 
Excel.ApplicationClass excel =
new Excel.ApplicationClass();
excel.Visible=true;
Excel.Workbook theWorkbook = excel.Workbooks.Open("C:\\Samp.xls",0,true,5,"","",true,Excel.XlPlatform.xlWindows,"\t",false,false,
0,true,true,false);
Excel.Sheets sheets = theWorkbook.Worksheets;
 
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
 
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "D" + i.ToString());

System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
for(int j=0;j
GeneralRe: excel.get_Workbooks() method doesn't existmemberKarthikaG17 Jun '05 - 1:14 
I also encountered the same problem..see the following code..
I hope that would be useful..
 
Excel.ApplicationClass excel =
new Excel.ApplicationClass();
excel.Visible=true;
Excel.Workbook theWorkbook = excel.Workbooks.Open("C:\\Samp.xls",0,true,5,"","",true,Excel.XlPlatform.xlWindows,"\t",false,false,
0,true,true,false);
Excel.Sheets sheets = theWorkbook.Worksheets;
 
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
 
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "D" + i.ToString());

System.Array myvalues = (System.Array)range.Cells.Value2;
string[] strArray = ConvertToStringArray(myvalues);
for(int j=0;j
GeneralRe: excel.get_Workbooks() method doesn't existmemberLars-Inge Tønnessen25 Jun '05 - 12:45 
Dp you use C# or VB.NET ?
 
C#/VB.NET does not use aaa = get_nnn(); or set_nnn(aaa);, but aaa = nnn and nnn = aaa;
 

"get_Workbooks()" should be "Workbooks" in C#.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 14 Nov 2004
Article Copyright 2004 by Lars-Inge Tønnessen
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid