在實際應用中,常常會遇到單元格的值比較長而被遮住,用戶不得不手動調整寬度,如果能通過程序就自動調整寬度就會很方便了。實際上在通過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