首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 计算机考试 > 认证考试 > JAVA认证 >

核心技术:在SWT中使用OLE操纵Excel(4)

2009-02-02 
SWTOLE

    使单元格或列自动调整宽度
  在实际应用中,常常会遇到单元格的值比较长而被遮住,用户不得不手动调整宽度,如果能通过程序就自动调整宽度就会很方便了。实际上在通过OleView.exe这个工具查询得知Range有AutoFit的方法,它的Id是0x000000ed,那么如果获得了Range的引用,只要调用AutoFit这个方法,就可以自动调整宽度了。下面请看代码与示例效果:
  package com.jrkui.example.excel;
  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.widgets.Display;
  import org.eclipse.swt.widgets.Shell;
  publicclass AutofitShell {
  publicstaticvoid main(String[] args) {
  new AutofitShell().open();
  }
  publicvoid open()
  {
  Display display = Display.getDefault();
  Shell shell = new Shell();
  shell.setText("Auto Fit");
  shell.setSize(700, 300);
  shell.setLayout(new FillLayout());
  createExcelPart(shell);
  shell.open();
  while(!shell.isDisposed())
  if(!display.readAndDispatch())
  display.sleep();
  display.dispose();
  }
  privatestaticfinalintSHEET_ID = 0x000001e5;
  privatestaticfinalintCELL_ID = 0x000000c5;
  privatestaticfinalintCELL_VALUE_ID = 0x00000006;
  privatevoid createExcelPart(Shell shell)
  {
  OleFrame frame = new OleFrame(shell,SWT.NONE);
  OleClientSite clientSite = new OleClientSite(frame,SWT.NONE,"Excel.Sheet");
  clientSite.doVerb(OLE.OLEIVERB_SHOW);
  OleAutomation workbook = new OleAutomation(clientSite);
  OleAutomation worksheet = workbook.getProperty(SHEET_ID,new Variant[]{new Variant(1)}).getAutomation();
  OleAutomation cellA3 = worksheet.getProperty(CELL_ID,new Variant[]{new Variant("A3")}).getAutomation();
  cellA3.setProperty(CELL_VALUE_ID, new Variant("if you don’t fit the width of the cell, you couldn’t see all."));
  autoFitWidth(cellA3);
  // autoFitWidth(getColumnOfCell(cellA3));
  }
  publicstaticfinalintAUTO_FIT_RANGE = 0x000000ed;
  /**
  *自适应宽度
  *@paramautomation
  */
  privatevoid autoFitWidth(OleAutomation automation)
  {
  //如果使用automation.getProperty(AUTO_FIT_RANGE)也是同样的效果
  automation.invoke(AUTO_FIT_RANGE);
  }
  publicstaticfinalintCOLUMN_OF_CELL = 0x000000f6;
  /**
  *获得单元格所在的列
  *@paramcell
  *@return
  */
  private OleAutomation getColumnOfCell(OleAutomation cell)
  {
  return cell.getProperty(COLUMN_OF_CELL).getAutomation();
  }
  }
  (自动调整A3单元格的宽度):
  (去掉createExcelPart()方法中的autoFitWidth(getColumnOfCell(cellA3));的注释,自动调整A3单元格所在列的列宽)
  说明:
  调整列宽在本例中是通过autoFitWidth(OleAutomation automation)方法
  在autoFitWidth(OleAutomation automation)中调用了OleAutomation的invoke()方法,参数是所代表ole对象的方法的id,意思是调用该方法,用 automation.getProperty(AUTO_FIT_RANGE)也是同样的效果
  autoFitWidth(OleAutomation automation)的参数是一个Range对象,可以是一个单元格,也可以是一个单元格的区域,在本例中示范了两种效果(单元格、列)
  获得一个单元格区域的的所在列的方法在Range中是Range* EntireColumn(),其id是0x000000f6

 


3COME考试频道为您精心整理,希望对您有所帮助,更多信息在http://www.reader8.com/exam/

热点排行