Cara membuat/Format buku kerja Excel yang menggunakan Visual J ++ otomatisasi

Terjemahan Artikel Terjemahan Artikel
ID Artikel: 219430 - Melihat produk di mana artikel ini berlaku.
Perbesar semua | Perkecil semua

RINGKASAN

Artikel ini menjelaskan Automating Excel 97 atau yang lebih baru dari Visual J ++ klien menggunakan Java bahasa pemrograman. Proyek menggunakan Excel Perpustakaan jenis, dan menggambarkan pemrograman berorientasi objek.

INFORMASI LEBIH LANJUT

Artikel ini sejajar dengan artikel Basis Pengetahuan Microsoft yang menjelaskan proses yang sama menggunakan Microsoft Visual C++ dan Microsoft Foundation Kelas. Untuk informasi tambahan tentang otomatisasi dari Excel dari Visual C++, klik nomor artikel di bawah ini untuk melihat artikel di dalam Basis Pengetahuan Microsoft:
179706Cara menggunakan MFC untuk mengotomatisasi Excel dan membuat/Format buku kerja baru
  1. Mulai Visual J ++ 6.0. Membuat aplikasi konsol baru proyek dan nama XLJava1.
  2. Di jendela proyek-Explorer, buka pohon proyek Anda dan Klik dua kali file Class1.java yang dibuat untuk Anda.
  3. Dari Project menu, pilih Tambahkan COM Wrapper, pilih Perpustakaan objek Microsoft Excel 8.0, 9.0, atau 10,0 (yang sesuai), lalu klik Oke. Ini menambah Jawa COM pembungkus yang berasal dari jenis Excel perpustakaan untuk proyek Anda.
  4. Di atas file Class1.Java Anda, tambahkan berikut impor pernyataan:
    
       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. Dalam Class1 entry point dan fungsi main(), tambahkan kode sehingga program Anda muncul sebagai berikut:
         /**
     * 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. Dari Debug menu, klik Mulai. Program membangun, paket, dan berjalan. Ketika berjalan, konsol jendela muncul dan beberapa waktu kemudian Excel muncul. Kotak dialog yang mendorong Anda pada Bagaimana mungkin Quarters bagan akan muncul di atas kecuali jika Anda mengklik di mana saja Anda layar setelah program dimulai. Jika Anda mengklik layar kotak dialog akan diminimalkan pada Windows task bar. Jika program muncul hang, memulihkan 'Normal' kotak dialog yang ada di task bar.

REFERENSI

Untuk informasi tambahan tentang Visual J ++ dan otomatisasi, klik nomor artikel di bawah ini untuk melihat artikel di dalam Basis Pengetahuan Microsoft:
169173INFO: Tanya jawab untuk Visual J ++
215484 Cara mengotomatisasi PowerPoint menggunakan Visual J ++
179706 Cara menggunakan MFC untuk mengotomatisasi Excel dan membuat/Format buku kerja baru
219151 Cara mengotomatisasi Microsoft Excel dari Visual Basic

Properti

ID Artikel: 219430 - Kajian Terakhir: 19 September 2011 - Revisi: 2.0
Berlaku bagi:
  • Microsoft Visual J++ 6.0 Standard Edition
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Excel 2000 Standard Edition
  • Microsoft Excel 97 Standard Edition
  • Microsoft Office XP Developer Edition
  • Microsoft Office 2000 Developer Edition
Kata kunci: 
kbautomation kbhowto kbmt KB219430 KbMtid
Penerjemahan Mesin
PENTING: Artikel ini diterjemahkan menggunakan perangkat lunak mesin penerjemah Microsoft dan bukan oleh seorang penerjemah. Microsoft menawarkan artikel yang diterjemahkan oleh seorang penerjemah maupun artikel yang diterjemahkan menggunakan mesin sehingga Anda akan memiliki akses ke seluruh artikel baru yang diterbitkan di Pangkalan Pengetahuan (Knowledge Base) dalam bahasa yang Anda gunakan. Namun, artikel yang diterjemahkan menggunakan mesin tidak selalu sempurna. Artikel tersebut mungkin memiliki kesalahan kosa kata, sintaksis, atau tata bahasa, hampir sama seperti orang asing yang berbicara dalam bahasa Anda. Microsoft tidak bertanggung jawab terhadap akurasi, kesalahan atau kerusakan yang disebabkan karena kesalahan penerjemahan konten atau penggunaannya oleh para pelanggan. Microsoft juga sering memperbarui perangkat lunak mesin penerjemah.
Klik disini untuk melihat versi Inggris dari artikel ini:219430

Berikan Masukan

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com