2011-02-09 119 views

回答

2

你想要修改的文件格式是什麼格式? (OLE2,WordML,docx?)

通常,最廣泛使用的MSOffice文件修改庫是Apache POI

另外this tutorial可能會對您目前的情況有所幫助。

2

只是一個想法:

起初,你將需要下載WordAPI,它可以正確here下載。用JAVA創建word文檔,有一個類可以處理你需要的一切。這個班級被稱爲WordProcessing

下面是在類中實現的方法的簡短預覽:

  • createNewDocumentFromTemplate(字符串TEMPLATENAME)
  • createNewDocumentFromTemplateToSelectByUser()
  • setNoteNotMatchingBookmarks(布爾noteNotMatchingBookmarks)
  • typeTextAtBookmark(字符串書籤,字符串textToType)
  • typeTextAtBookmark(String bookmark,String [] linesToType)
  • changeDocumentDirectory(字符串documentDirectory)
  • saveDocumentAs(字符串documentName)
  • saveDocumentAsAndClose(字符串documentName)
  • closeDocument()
  • printAndForget()
  • printToPrinterToSelectByUserAndForget()
  • printAndForget(字符串PRINTERNAME)
  • executeMacro(String macroName)< ----感興趣的是你
  • quitApplication()
  • EXEC()

正如你可以看到有很多有用的功能來創建文檔。

現在您可以通過調用executeMacro函數來插入圖像。

宏看起來是這樣的:

Option Explicit 

Sub InsertPicture() 

    Dim sPath As String 
    Dim sBildPfad As String 
    Dim lRes As Long 

    'The path of your picture 
    sBildPfad = "C:\temp" 

    'remember the current path of the picture 
    sPath = Options.DefaultFilePath(Path:=wdPicturesPath) 

    'changing the path 
    Options.DefaultFilePath(Path:=wdPicturesPath) = sBildPfad 

    'open dialog 
    lRes = Application.Dialogs(wdDialogInsertPicture).Show 

    'reset path 
    Options.DefaultFilePath(Path:=wdPicturesPath) = sPath 

    If lRes <> 0 And ActiveDocument.InlineShapes.Count > 0 Then 
     'if inserted, changing the size 
     Call PicSize(ActiveDocument.InlineShapes(ActiveDocument.InlineShapes.Count)) 
    End If 

End Sub 

Sub PicSize(oPic As InlineShape) 
    Dim iScale As Single 
    Dim iWidth As Single 

    iWidth = 200 ' (pixel) 

    oPic.LockAspectRatio = msoTrue 
    ' scaling 
    iScale = (iWidth/oPic.Width) * 100 
    oPic.ScaleWidth = iScale 
    oPic.ScaleHeight = iScale 
End Sub 
+0

參數macroname,應該包含宏的代碼,如果不是,我們怎麼能通過它? – 2013-07-24 11:08:04

1

假設DOCX是OK,你可以使用docx4j。該AddImage樣品包括:

org.docx4j.wml.P p = newImage(wordMLPackage, bytes, 
      filenameHint, altText, 
      id1, id2); 
// Now add our p to the document 
wordMLPackage.getMainDocumentPart().addObject(p); 

沒有需要運行Word的docx4j工作。

ps由於您的問題被標記爲「擺動」,您可能希望谷歌「docx4all」爲使用Swing實現的docx文字處理器,該處理器顯示圖像。

+0

我試過了,但是我沒有成功。 AddImage.java文件有什麼用處。我經歷了代碼,但我沒有明確的想法。請你解釋一下這段代碼的用法。 – jcrshankar 2011-03-11 14:03:36