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());
}
}
使Excel嵌入到SWT窗口中(2)
内容版权声明:除非注明,否则皆为本站原创文章。