在实际应用中,常常会遇到单元格的值比较长而被遮住,用户不得不手动调整宽度,如果能通过程序就自动调整宽度就会很方便了。实际上在通过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();
}
}