2008年2月5日火曜日

Java-Com Bridgeを使う(PowerPoint編)

例えば以下のようなSubプロシージャがある

===========================================================
Private Sub RemoveTextInShape(thisShape As Shape)
If thisShape.HasTextFrame = msoTrue Then
thisShape.TextFrame.TextRange.Text = RemoveInText(InjectCharacters(thisShape.TextFrame.TextRange.Text))
End If

If thisShape.HasTable = msoTrue Then
Dim thisRows As Rows
Set thisRows = thisShape.Table.Rows
Dim thisRow As Row
For Each thisRow In thisRows
Dim thisCells As CellRange
Set thisCells = thisRow.Cells
Dim thisCell As Cell
For Each thisCell In thisCells
RemoveTextInShape thisCell.Shape
Next
Next
End If
End Sub

===========================================================

これをJava-Com Bridgeを使用してJava流に書き直すと以下のようになる

===========================================================

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String openUrl = "C:\\java_test\\sample.ppt";

oPPT = new ActiveXComponent("PowerPoint.Application");

try{

oPPT.setProperty("Visible", new Variant(true));
Object oPresentations = oPPT.getProperty("Presentations").toDispatch();
Object oPresentation = Dispatch.call(oPresentations, "Open", openUrl).toDispatch();
Object oActivePresentation = oPPT.getProperty("ActivePresentation").toDispatch();
Object oSlides = oPPT.call(oActivePresentation, "Slides").toDispatch();
int totalSlides = oPPT.call(oSlides, "Count").toInt();

//Slideの配列を作成する
ArrayList<Object> thisSlides = new ArrayList<Object>();
for (int i = 1; i < totalSlides + 1; i++){

Object slideObj = oPPT.call(oActivePresentation, "Slides", new Variant(i)).toDispatch();
thisSlides.add(slideObj);
}

System.out.println("スライドの総数は " + thisSlides.size());
for(int i = 0; i < thisSlides.size(); i++){

System.out.println("Slide ID: " + oPPT.call(thisSlides.get(i), "SlideID").toInt());
Object oShape = oPPT.call(thisSlides.get(i), "Shapes").toDispatch();
int totalShapes = oPPT.call(oShape, "Count").toInt();
//System.out.println("totalShapesは " + totalShapes);

//個々のshapeに対して実行する。
for (int n = 1; n < totalShapes + 1; n++){
Object shapeObj = oPPT.call(thisSlides.get(i), "Shapes", new Variant(n)).toDispatch();
removeTextInshape(shapeObj);
}

}
Dispatch.call(oPresentation, "Save");

} catch (ComFailException e){
System.err.println(e.getMessage() + e.getHResult());
} finally {
Dispatch.call(oPPT, "Quit");
ComThread.Release();
}

}

private static ActiveXComponent oPPT;

===========================================================

要は Object slideObj = oPPT.call(oActivePresentation, "Slides", new Variant(i)).toDispatch(); をスライドの数だけループし、いちいちSlides配列を作成する必要がある。とっても面倒くさい。。

0 件のコメント:

自己紹介

最近気胸になりました。でタバコやめました。