在SWT中使用OLE操纵Excel(二)
来源:优易学  2011-1-24 14:40:30   【优易学:中国教育考试门户网】   资料下载   IT书店

  为Excel的A1单元格赋值
  代码:
  package com.jrkui.example.excel;
  import java.io.File;
  import org.eclipse.swt.SWT;
  import org.eclipse.swt.layout.FillLayout;
  import org.eclipse.swt.ole.win32.OLE;
  import org.eclipse.swt.ole.win32.OleAutomation;
  import org.eclipse.swt.ole.win32.OleClientSite;
  import org.eclipse.swt.ole.win32.OleFrame;
  import org.eclipse.swt.ole.win32.Variant;
  import org.eclipse.swt.program.Program;
  import org.eclipse.swt.widgets.Display;
  import org.eclipse.swt.widgets.Menu;
  import org.eclipse.swt.widgets.Shell;
  public class ExcelShell {
  public static void main(String[] args) {
  new ExcelShell().open();
  }
  public void open()
  {
  Display display = Display.getDefault();
  Shell shell = new Shell();
  shell.setSize(600,400);
  shell.setText("Excel Window");
  shell.setLayout(new FillLayout());
  //使Excel的菜单栏显示
  shell.setMenuBar(new Menu(shell,SWT.BAR));
  createExcelPart(shell);
  shell.open();
  while(!shell.isDisposed()){
  if(!display.readAndDispatch())
  display.sleep();
  }
  display.close();
  }
  /**
  * 使Excel嵌入到shell中
  * @param shell
  */
  private void createExcelPart(Shell shell)
  {
  //OleFrame实际上是一个Composite,用于放置OLE控件
  OleFrame oleFrame = new OleFrame(shell,SWT.NONE);
  //OleClientSite提供一个场所用于把OLE对象嵌入到容器中,在这里“Excel.Sheet”表示的OLE对象是Excel
  OleClientSite clientSite = new OleClientSite(oleFrame,SWT.NONE,"Excel.Sheet");
  setValueForA1Cell(clientSite);
  //OleClientSite在显示OLE对象时所做的动作,这里的动作是OLEIVERB_SHOW,显示
  clientSite.doVerb(OLE.OLEIVERB_SHOW);
  }
  /**
  * Sheet的Id
  */
  private static final int SHEET_ID = 0x000001e5;
  /**
  * 单元格的Id
  */
  private static final int CELL_ID = 0x000000c5;
  /**
  * 单元格值的Id
  */
  private static final int CELL_VALUE_ID = 0x00000006;
  /**
  * 为第一个Sheet页的A1单元格赋值
  * @param clientSite
  */
  private void setValueForA1Cell(OleClientSite clientSite)
  {
  //获得Excel的workbook对象
  OleAutomation workbook = new OleAutomation(clientSite);
  //获得workbook的第一个Sheet页
  OleAutomation sheet = workbook.getProperty(SHEET_ID,new Variant[]{new Variant(1)}).getAutomation();
  //获得Sheet页的A1单元格
  Variant cellA1Variant = sheet.getProperty(CELL_ID, new Variant[]{new Variant("A1")});
  OleAutomation cellA1 = cellA1Variant.getAutomation();
  //为A1单元格赋值
  cellA1.setProperty(CELL_VALUE_ID, new Variant("Hello OLE!"));
  //获得A1单元格的值并输出到控制台上
  System.out.println(cellA1Variant.getString());
  }
  }
  控制台输出:Hello OLE!

[1] [2] 下一页

责任编辑:小草

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