How To Create/Format an Excel Workbook Using Visual J++ Automation (219430)



The information in this article applies to:

  • Microsoft Visual J++ 6.0
  • Microsoft Office Excel 2003
  • Microsoft Excel 2002
  • Microsoft Excel 2000
  • Microsoft Excel 97 for Windows
  • Microsoft Office XP Developer
  • Microsoft Office 2000 Developer

This article was previously published under Q219430

SUMMARY

This article describes Automating Excel 97 or later from a Visual J++ client using the Java programming language. The project uses the Excel type library, and illustrates object oriented programming.

MORE INFORMATION

This article parallels a Microsoft Knowledge Base article that describes the same process using Microsoft Visual C++ and Microsoft Foundation Classes. For additional information about Automation of Excel from Visual C++, click the following article number to view the article in the Microsoft Knowledge Base:

179706 How To Use MFC to Automate Excel and Create/Format a New Workbook

  1. Start Visual J++ 6.0. Create a new Console Application project and name it XLJava1.
  2. In the Project-Explorer window, open your Project tree and double-click the Class1.java file created for you.
  3. From the Project menu, choose Add COM Wrapper, select the Microsoft Excel 8.0, 9.0, or 10.0 (as appropriate) Object Library, and then click OK. This adds Java COM Wrappers that are derived from the Excel type library to your project.
  4. At the top of your Class1.Java file, add the following import statements:
    
       import Excel8.*; // Change the 8 to 9 for Excel 2000, or 10 for 2002 or later
       // For Excel 2000 the statement should read
       // import Excel9.*; // Excel support
       import com.ms.com.*; // Variant & exception support. 
       import java.lang.InterruptedException; // Needed for Thread.sleep().
       (These are illustrated in the code sample below.)
    					
  5. In the Class1 entry point and the main() function, add code so that your program appears as follows:
         /**
     * This class can take a variable number of parameters on the command
     * line. Program execution begins with the main() method. The class
     * constructor is not invoked unless an object of type 'Class1'
     * created in the main() method.
     */ 
    import excel.*; // for Excel 2002, or - import excel9.*; for Excel 2000 or later
                      // or - import excel8.*; for Excel 97
    import java.lang.InterruptedException; // needed for thread.sleep
    import com.ms.com.*; // Variant & exception support<BR/>
    public class Class1
    {
    	/**
    	 * The main entry point for the application. 
    	 *
    	 * @param args Array of parameters passed to the application
    	 * via the command line.
    	 */ 
    	//==============================================================
    	// Add the following static member function declaration 
        // just before main()...
        // J/Direct declarations... to use Windows MessageBox
        /** @dll.import("USER32") */ 
        private static native int MessageBox(int hwndOwner, String text, 
                                             String title, int fuStyle);
        // Here is an example of its use.
        // MessageBox(0, "Hello, World", "Title", 0); //fuStyle switch
        //    values are defined in Winuser.h. Search on 'MB_OK'
        //==============================================================
    	public static void main (String[] args)
    	{
    		// Force COM objects to be created on the current thread.
          // Otherwise, older VMs might not release all references
          // and Excel might continue to run after you shutdown.
          ComLib.declareMessagePumpThread();
          // Launch Excel 
          Variant vEmpty = new Variant();
          vEmpty.noParam();
          Application xlApp = new Application();
          //xlApp.setVisible(0,true); // Excel 2000 & 97 1st param is LCID, Locale ID
    	  xlApp.setVisible(true); // One argument for Excel 2002 or later
       	
          // Get the workbook object via the object model.
          Workbooks books = xlApp.getWorkbooks();
          _Workbook book = books.Add(vEmpty,0);
          // Get the first sheet.		
          Sheets sheets = (Sheets)book.getSheets();
          _Worksheet sheet = (_Worksheet)sheets.getItem(new Variant(1));
          // Fill cells A1, B1, C1, and D1, one cell at a time, with "headers".
          Range range = sheet.getRange(new Variant("A1"),new Variant("A1"));
          //range.setValue(new Variant("First Name")); // Throughout, the SetValue
          // of Excel 97 and Excel 2000 no longer works in Excel 2002 or later.
    	  range.setValue2(new Variant("First Name"));
          range = sheet.getRange(new Variant("B1"),new Variant("B1"));
          //range.setValue(new Variant("Last Name"));
    	  range.setValue2(new Variant("Last Name"));
          range = sheet.getRange(new Variant("C1"),new Variant("C1"));
          //range.setValue(new Variant("Full Name"));
    	  range.setValue2(new Variant("Full Name"));
          range = sheet.getRange(new Variant("D1"),new Variant("D1"));
          //range.setValue(new Variant("Salary"));
    	  range.setValue2(new Variant("Salary"));
          // Format A1:D1 as bold, vertical alignment = center
          range = sheet.getRange(new Variant("A1"),new Variant("D1"));
          Font font = range.getFont();
          font.setBold(new Variant(true));
          range.setVerticalAlignment(new Variant(-4108));
          // Fill range A2:B6 with first and last names, 
          range = sheet.getRange(new Variant("A2"),new Variant("A2"));
          //range.setValue(new Variant("John"));
    	  range.setValue2(new Variant("John"));
          range = sheet.getRange(new Variant("B2"),new Variant("B2"));
          //range.setValue(new Variant("Smith"));
    	  range.setValue2(new Variant("Smith"));
          range = sheet.getRange(new Variant("A3"),new Variant("A3"));
          //range.setValue(new Variant("Tom"));
    	  range.setValue2(new Variant("Tom"));
          range = sheet.getRange(new Variant("B3"),new Variant("B3"));
          //range.setValue(new Variant("Brown"));
    	  range.setValue2(new Variant("Brown"));
          range = sheet.getRange(new Variant("A4"),new Variant("A4"));
          //range.setValue(new Variant("Sue"));
    	  range.setValue2(new Variant("Sue"));
          range = sheet.getRange(new Variant("B4"),new Variant("B4"));
          //range.setValue(new Variant("Thomas"));
    	  range.setValue2(new Variant("Thomas"));
          range = sheet.getRange(new Variant("A5"),new Variant("A5"));
          //range.setValue(new Variant("Jane"));
    	  range.setValue2(new Variant("Jane"));
          range = sheet.getRange(new Variant("B5"),new Variant("B5"));
          //range.setValue(new Variant("Jones"));
    	  range.setValue2(new Variant("Jones"));
          range = sheet.getRange(new Variant("A6"),new Variant("A6"));
          //range.setValue(new Variant("Adam"));
    	  range.setValue2(new Variant("Adam"));
          range = sheet.getRange(new Variant("B6"),new Variant("B6"));
          //range.setValue(new Variant("Johnson"));
    	  range.setValue2(new Variant("Johnson"));
          // Fill range C2:C6 with a relative formula(=A2 & " " & B2")
          range = sheet.getRange(new Variant("C2"),new Variant("C6"));
          range.setFormula(new Variant("=A2 & \" \" & B2"));
          // Fill D2:D6 with a formula (=RAND()*100000) and apply a 
          //  number format
          range = sheet.getRange(new Variant("D2"),new Variant("D6"));
          range.setFormula(new Variant("=RAND()*100000"));
          range.setNumberFormat(new Variant("$0.00"));
          // AutoFit columns A:D
          range = sheet.getRange(new Variant("A1"),new Variant("D1"));
          Range columns = range.getEntireColumn();
          columns.AutoFit();
          // Manipulate a variable number of columns
          //  for Quarterly Sales Data
          short NumQtrs;
          String msg;
          String msg2;
          msg2 = " "; // Initialize it to avoid compile error
          int reply;
          Range resizedrange;
          Interior interior;
          Borders borders;
          // Determine how many quarters to display data for.
          for(NumQtrs = 1; NumQtrs<=4; NumQtrs++)
          {
             if (NumQtrs == 1)
             {
              msg = "Enter sales data for " + NumQtrs + " quarter?";
              msg2 = "Displaying data for " + NumQtrs + " quarter";
             }
             else
             {
              msg = "Enter sales data for " + NumQtrs + " quarters?";
              msg2 = "Displaying data for " + NumQtrs + " quarters";
             }
             reply = MessageBox(0, msg, "Indicate Quarters", 36);
             if(6 == reply) break;			
          } // end For loop
       		
          MessageBox(0, msg2, "Data Setting", 0);
          if(5 == NumQtrs) // Limit display to <=4 quarters
          {
           NumQtrs = 4;
          }
          // Starting at E1, fill headers for number of columns selected.
          range = sheet.getRange(new Variant("E1"),new Variant("E1"));
          resizedrange = range.getResize(vEmpty, new Variant(NumQtrs));
          resizedrange.setFormula(
             new Variant("= \"Q\" & COLUMN()-4 & CHAR(10)& \"Sales\""));
          // Change the Orientation and Wrap Text properties for the headers.
          resizedrange.setOrientation(new Variant(38));
          resizedrange.setWrapText(new Variant(true));
          // Fill the interior colors of the headers.
          interior = resizedrange.getInterior();
          interior.setColorIndex(new Variant(36));
          // Fill the columns with a formula and apply a number format.
          range = sheet.getRange(new Variant("E2"),new Variant("E6"));
          resizedrange = range.getResize(vEmpty, new Variant(NumQtrs));
          resizedrange.setFormula(new Variant("=RAND()*100"));
          resizedrange.setNumberFormat(new Variant("$0.00"));
          // Apply Borders to the Sales data and headers
          range = sheet.getRange(new Variant("E1"), new Variant("E6"));
          resizedrange = range.getResize(vEmpty, new Variant(NumQtrs));
          borders = resizedrange.getBorders();
          borders.setWeight(new Variant(2)); // xlThin = 2
          // Add Totals formula for Quarterly sales data, apply a border.
          range = sheet.getRange(new Variant("E8"),new Variant("E8"));
          resizedrange = range.getResize(vEmpty, new Variant(NumQtrs));
          resizedrange.setFormula(new Variant("=SUM(E2:E6)"));
          borders = resizedrange.getBorders();
          Border bottomborder;
          bottomborder = borders.getItem(9); // Bottom border
          bottomborder.setLineStyle(new Variant(-4119)); // xlDouble = -4119
          bottomborder.setWeight(new Variant(4));  // xlThick = 4
          // Some more features: Add comment to cell C3 - Full 
          //    name of Tom Brown
          range = sheet.getRange(new Variant("C3"),new Variant("C3"));
          range.AddComment(new Variant("Tom was last month's top performer"));
          // Chart the Salaries.
          double Left = 72.; // location in points
          double Top = 144.;
          double Width = 350.;
          double Height = 250.;
          ChartObjects chartobjects = 
            (ChartObjects)sheet.ChartObjects(vEmpty,0); // explicit typecast
          ChartObject chartobject = chartobjects.Add(Left, Top, Width, Height);
          // Set the location and size.
          Chart chart = chartobject.getChart();
          range = sheet.getRange(new Variant("C2"), new Variant("D6"));
          // Full name and salary.
          range.Select();
          chart.ChartWizard(new Variant(range), // Source
                            new Variant(11),    // Gallery
                            vEmpty,             // Format
                            new Variant(1),     // PlotBy
                            new Variant(0),     // CategoryLabels
                            new Variant(1),     // SeriesLabels
                            new Variant(true),  // HasLegend
                            new Variant("Salary by Employee"), //Title
                            new Variant("Employee"), //CategoryTitle
                            new Variant("Salary"), //ValueTitle
                            vEmpty,             // ExtraTitle
                            0                   // LCID(localeID)
                            );
       		
          // Make the application visible and give the user control of 
          // Microsoft Excel.
          // xlApp.setVisible(0,true); // 1st param is LCID, Locale ID. 
          // The preceding was done at beginning of the program.
          xlApp.setUserControl(true);
       		
          MessageBox(0, "When Excel hides, Minimize VJ++ IDE to see Excel",
                     "Focus on Excel", 327744);
          //book.setSaved(0,true); // Avoid "Save changes" dialog
          //xlApp.Quit();  // Not if using UserControl		
    	} // End of Main()
    } // End of Class
    
    
    					
  6. From the Debug menu, click Start. The program builds, packages, and runs. When it runs, a Console window appears and some time later Excel appears. A dialog box prompting you on how may Quarters to chart will appear on top unless you click anywhere on your screen after the program starts. If you have clicked the screen the dialog box will be minimized on the Windows task bar. If the program appears to hang, restore to 'Normal' the dialog box that is on your task bar.

REFERENCES

For additional information about Visual J++ and Automation, click the following article numbers to view the articles in the Microsoft Knowledge Base:

169173 INFO: Frequently Asked Questions for Visual J++

169796 How To Automate Excel from Java

215484 How To Automate PowerPoint Using Visual J++

179706 How To Use MFC to Automate Excel and Create/Format a New Workbook

219151 How To Automate Microsoft Excel from Visual Basic


Modification Type:MinorLast Reviewed:6/30/2004
Keywords:kbAutomation kbhowto KB219430 kbAudDeveloper