为Excel的A1单元格赋值
来源:优易学  2011-2-9 13:19:17   【优易学:中国教育考试门户网】   资料下载   IT书店

  代码:
  packagecom.jrkui.example.excel;
  importjava.io.File;
  importorg.eclipse.swt.SWT;
  importorg.eclipse.swt.layout.FillLayout;
  importorg.eclipse.swt.ole.win32.OLE;
  importorg.eclipse.swt.ole.win32.OleAutomation;
  importorg.eclipse.swt.ole.win32.OleClientSite;
  importorg.eclipse.swt.ole.win32.OleFrame;
  importorg.eclipse.swt.ole.win32.Variant;
  importorg.eclipse.swt.program.Program;
  importorg.eclipse.swt.widgets.Display;
  importorg.eclipse.swt.widgets.Menu;
  importorg.eclipse.swt.widgets.Shell;
  publicclassExcelShell{
  publicstaticvoidmain(String[]args){
  newExcelShell().open();
  }
  publicvoidopen()
  {
  Displaydisplay=Display.getDefault();
  Shellshell=newShell();
  shell.setSize(600,400);
  shell.setText("ExcelWindow");
  shell.setLayout(newFillLayout());
  //使Excel的菜单栏显示
  shell.setMenuBar(newMenu(shell,SWT.BAR));
  createExcelPart(shell);
  shell.open();
  while(!shell.isDisposed()){
  if(!display.readAndDispatch())
  display.sleep();
  }
  display.close();
  }
  /**
  *使Excel嵌入到shell中
  *@paramshell
  */
  privatevoidcreateExcelPart(Shellshell)
  {
  //OleFrame实际上是一个Composite,用于放置OLE控件
  OleFrameoleFrame=newOleFrame(shell,SWT.NONE);
  //OleClientSite提供一个场所用于把OLE对象嵌入到容器中,在这里“Excel.Sheet”表示的OLE对象是Excel
  OleClientSiteclientSite=newOleClientSite(oleFrame,SWT.NONE,"Excel.Sheet");
  setValueForA1Cell(clientSite);
  //OleClientSite在显示OLE对象时所做的动作,这里的动作是OLEIVERB_SHOW,显示
  clientSite.doVerb(OLE.OLEIVERB_SHOW);
  }
  /**
  *Sheet的Id
  */
  privatestaticfinalintSHEET_ID=0x000001e5;
  /**
  *单元格的Id
  */
  privatestaticfinalintCELL_ID= 0x000000c5;
  /**
  *单元格值的Id
  */
  privatestaticfinalintCELL_VALUE_ID=0x00000006;
  /**
  *为第一个Sheet页的A1单元格赋值
  *@paramclientSite
  */
  privatevoidsetValueForA1Cell(OleClientSiteclientSite)
  {
  //获得Excel的workbook对象
  OleAutomationworkbook=newOleAutomation(clientSite);
  //获得workbook的第一个Sheet页
  OleAutomationsheet=workbook.getProperty(SHEET_ID,newVariant[]{newVariant(1)}).getAutomation();
  //获得Sheet页的A1单元格
  VariantcellA1Variant=sheet.getProperty(CELL_ID,newVariant[]{newVariant("A1")});
  OleAutomationcellA1=cellA1Variant.getAutomation();
  //为A1单元格赋值
  cellA1.setProperty(CELL_VALUE_ID,newVariant("HelloOLE!"));
  //获得A1单元格的值并输出到控制台上
  System.out.println(cellA1Variant.getString());
  }
  }
  显示效果:

[1] [2] [3] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训