導航:首頁 > 編程語言 > java寫word

java寫word

發布時間:2023-11-29 03:24:25

java如何根據word模板生成word文檔

首先是action的createDoc方法:
[java]
/**
* 通過HttpCient調用報告伺服器的方法生成報告 DOC
*/
public String createDoc() throws Exception {
//定義放回成功與否的判斷碼
String prMsg="";
// 獲取當前登錄的用戶
UserVo userVo = CommonUtils.getUserMessage();
//獲取模版類型
docType = Struts2Utils.getParameter("docType");
//重新創建文檔
String creatOrnot = Struts2Utils.getParameter("creatOrnot");
//獲取組組編號參數
workgroupId = Struts2Utils.getParameter("workgroupId");
//獲取評估用例實例ID參數
evtcaseInstId = Struts2Utils.getParameter("evtcaseInstId");
if(CommonUtils.isNotNull(docType)){
//獲取項目Id
projectId = Struts2Utils.getParameter("projectId");
if(!CommonUtils.isNotNull(projectId)){
if(CommonUtils.isNotNull(this.getIdFromSession("PM_PROJECTID"))){
projectId = this.getIdFromSession("PM_PROJECTID").toString();
}else{
Struts2Utils.getRequest().setAttribute("msg", "請先選擇項目!");
}
}
if(CommonUtils.isNotNull(projectId)){
prMsg = infoSystemDescService.downloadFileByUrl(projectId, userVo.getUserId(), workgroupId, evtcaseInstId, docType, creatOrnot);
}
}
return "docList";
}
註:在我貼出來的代碼中,能看懂就行了,有些不用管他(可能是其他業務方面的判斷),關於最後返回的prMsg---代表各種狀態 主要表示成功與否或者是出錯的信息。

接著我貼出service層的方法downloadFileByUrl

[java]
</pre><p></p><p></p><pre name="code" class="java"><pre name="code" class="java">/**
* 功能:
* 1.(生成報告文檔)
* 2.保存指定URL的源文件到指定路徑下
* @param projectId
* @param userId
* @param workgroupId
* @param evtcaseInstId
* @param docType
* @param creatOrnot
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public synchronized String downloadFileByUrl(String projectId,String userId,String workgroupId,String evtcaseInstId,String docType,String creatOrnot) throws Exception {
String msg = "1";//"1":默認為創建成功的提示信息 "2":標識創建失敗
String srcUrl = ""; //報告伺服器的執行路徑
HttpResponse response = null;
FileOutputStream out = null;
HttpClient httpclient = null;
HttpGet httpget = null;
long time1 = System.currentTimeMillis();
//獲取保存後的路徑
TProjDoc projDoc = projectDocDao.findFileByType(userId, Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
if(projDoc == null || (projDoc != null && CommonUtils.isNotNull(creatOrnot) && creatOrnot.equals("1"))){ //FT_任務編號_[FID]
try {
//獲取報告伺服器的執行路徑
srcUrl = xmlPathDef.getActionUrl(docType, projectId,userId,workgroupId,evtcaseInstId);

HttpParams httpParams = new BasicHttpParams();
// 設置最大連接數
ConnManagerParams.setMaxTotalConnections(httpParams, 1);
// 設置獲取連接的最大等待時間
//ConnManagerParams.setTimeout(httpParams, 6000);
// 設置每個路由最大連接數
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(1);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);
// 設置連接超時時間
HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
// 設置讀取超時時間
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) && docType.toString().equals(XmlPathDef.FTEST_DOC)){
HttpConnectionParams.setSoTimeout(httpParams, 2400000);
}else{
HttpConnectionParams.setSoTimeout(httpParams, 600000);
}

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(httpParams, registry);

httpclient = new DefaultHttpClient(connectionManager, httpParams);

httpget = new HttpGet(srcUrl);
//執行返回
response = httpclient.execute(httpget);
//如果是本機既當伺服器,又當報表伺服器,那麼就只生成一遍
String ipvalues = xmlPathDef.getRepUrl();
if(CommonUtils.isNotNull(ipvalues)){
if(ipvalues.indexOf(":") != -1){
ipvalues = ipvalues.substring(0,ipvalues.lastIndexOf(":"));
}
}
HttpEntity entity = response.getEntity();
//獲取保存後的路徑
projDoc = projectDocDao.findFileByType(userId,Integer.parseInt(docType), Long.parseLong(projectId), workgroupId,evtcaseInstId);
String filePath = "";
if(projDoc != null)
filePath = projDoc.getPath();
if(CommonUtils.isNotNull(filePath)){
String basepath = XmlPathDef.getBasePath();
String outFilePath = (basepath + filePath).replaceAll("\\\\", "\\/");
XmlPathDef.isExists(outFilePath);
File wdFile = new File(outFilePath);
out = new FileOutputStream(wdFile);
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
out.close();
System.out.println("****************************** ");
System.out.println("");
System.out.println("*************** 恭喜! 報告創建成功 結束 ***************");
System.out.println("");
}else{
msg = "8";//說明word創建成功,但是數據沒有保存成功
response = null;
}
}else{
msg = "2";
}
} catch (ClientProtocolException e) {
msg = "7";
e.printStackTrace();
} catch (IOException e) {
msg = "7";
logger.error("資料庫報告伺服器地址配置錯誤或網路不通!!2.連接是否超時" + e.getMessage());
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
msg = "7";
logger.error("資料庫報告伺服器地址配置錯誤或網路不通!!2.連接是否超時" + e.getMessage());
e.printStackTrace();
}
}

}
}
long time2 = System.currentTimeMillis();
long numTime = time2 - time1;
if(docType.toString().equals(XmlPathDef.SPOTTEST_DOC) && docType.toString().equals(XmlPathDef.FTEST_DOC)){
if(numTime >= 2401000){
msg = "9";

}
}else{
if(numTime >= 601000){
msg = "9";
}
}
System.out.println("");
String loggerinfo = "********* 報告類型為 :" + docType + " 執行時間為: " + (time2 - time1) /1000 + " 秒!***************";
System.out.println(loggerinfo);
System.out.println("");
System.out.println("*****************************");
logger.info(loggerinfo);
return msg;
}

Ⅱ Java怎麼操作OpenOffice創建word文檔並向其設置內容

OpenOffice java api:

簡單的說就是利用java程序可以操作OpenOffice的所有功能,比如創建doc文檔,插入文字,設置文字格式等等。

1. OpenOffice 給程序員提供了一個叫UNO (UniversalNetwork Objects)的組件技術.我理解的UNO: OpenOffice 類似於web程序中的伺服器,程序員寫的代碼類似於客戶端,利用UNO提供的介面和服務去完成對OpenOffice文檔的操作。所以寫程序首先要搭建 UNO環境:

1. 下載 OpenOffice

2.復制UNO提供的jar包: unoil.jar, java_uno.jar, juh.jar, jurt.jar, ridl.jar, unoloader.jar. (ps: 安裝了SDK之後在文件夾找)到自己的工程中,引入它們。

3. 下載文檔:DevelopersGuide.pdf.

4. 安裝了SDK後,重新啟動一下機器,然後就可以按照 DevelopersGuide 來學習 UNO 編程了。

5. 需要ava 環境。

補充: 安裝了SDK後, java, c++幫助文檔,樣常式序,其他關於sdk的信息 都放在本地openOffice安裝路徑一個叫sdk目錄下面,enjoy it !

總結一下已經實現的功能和碰到的問題匯總:

1. 首先要得到遠程office組件的上下文.通過:

com.sun.star.uno.XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();

得到,如果OpenOffice安裝路徑不是在工程的路徑下面(我自己猜的), 就會報:

com.sun.star.comp.helper.BootstrapException: no office executable found!

解決辦法: 黑其源代碼, 看了源代碼就會發現其實OpenOffice是在尋找本地的soffice的shell文件,所以弄個變數來保存soffice在系統中的路徑,重新寫一 個Bootstrap就可以了。詳細請參照:論壇 。

2. 得到 XMultiComponentFactory (ComponentFactory 工廠)

com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();

3. 得到各種組件可以通過下面代碼:

// docType 是 與 soffice 同目錄下面的OpenOffice的其他shell文件,swrite等等

protected XComponent newDocComponent(String docType)
throws java.lang.Exception {
String loadUrl = "private:factory/" + docType;

mxRemoteServiceManager = this.getRemoteServiceManager();
Object desktop = mxRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", mxRemoteContext);

XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
PropertyValue[] loadProps = new PropertyValue[0];

return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0,
loadProps);
}

4.得到 XTextDocument

XComponent xEmptyWriterComponent = newDocComponent("swriter");

XTextDocument mxDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,
xEmptyWriterComponent);

5. 得到一個文檔的引用

XText mxDocText = mxDoc.getText();

6. 得到文檔的屬性列表

XPropertySet mxDocProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, mxDoc);

7. 建立游標,用來插入新的內容。

XTextCursor mxDocCursor = mxDocText.createTextCursor();

XSentenceCursor xSentenceCursor = (XSentenceCursor) UnoRuntime
.queryInterface(XSentenceCursor.class, mxDocCursor);

XWordCursor xWordCursor = (XWordCursor) UnoRuntime.queryInterface(
XWordCursor.class, mxDocCursor);

8.得到游標屬性列表

XPropertySet xCursorProps = (XPropertySet) UnoRuntime .queryInterface(XPropertySet.class, mxDocCursor);

9.設置插入文字格式

xCursorProps.setPropertyValue("CharFontName", "宋體");
xCursorProps.setPropertyValue("CharWeight", new Float(FontWeight.BOLD));
xCursorProps.setPropertyValue("CharHeight", new Float(10.5));
// 居中顯示
xCursorProps.setPropertyValue("ParaAdjust", com.sun.star.style.ParagraphAdjust.CENTER);

10.在該游標處插入信息

mxDocText.insertString(xSentenceCursor, 「Hello World", true);

11. 保存的關鍵代碼

protected void storeDocComponent(XComponent xDoc, String storeUrl)
throws java.lang.Exception {

XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
XStorable.class, xDoc);
PropertyValue[] storeProps = new PropertyValue[1];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = "MS Word 97";

openOfficeJavaLogger.debug("... store \"" + xDoc.toString() + "\" to \"" + storeUrl
+ "\".");

xStorable.storeAsURL(storeUrl, storeProps);

Ⅲ java 生成word用什麼方法好 poi 還是iText生成rtf

可以用jacob 這個是用java調用dll里的方法來操作word dll里的方法類似VBA
還可以用openoffice的api另存為word
iText沒用過 poi操作excel很方便 純文本的word還可以 有圖片 有表格的話就不行了
ps:java生成有表格的word好像都不是很好

閱讀全文

與java寫word相關的資料

熱點內容
程序員的設備有哪些 瀏覽:614
龍貓電影免費觀看普通話 瀏覽:253
pubg體驗服為什麼伺服器爆滿 瀏覽:62
鈑金編程排版哪裡有視頻可以參考 瀏覽:32
文件夾用於干什麼 瀏覽:510
如色房加密路線 瀏覽:42
阿帕奇web伺服器干什麼用 瀏覽:14
豆豆的書在哪個app可以看 瀏覽:431
基本的編程思想 瀏覽:979
app慕課在哪裡綁定微信 瀏覽:183
加密貨幣央行最新消息 瀏覽:974
伺服器L12是什麼意思 瀏覽:405
關於大海的英語電影 瀏覽:564
日本推理電影榜 瀏覽:571
快手上的影視小短片哪裡找的 瀏覽:59
大香蕉人在線觀看1 瀏覽:922
android獲得根目錄 瀏覽:95
文件目錄類命令有哪些 瀏覽:174
宅男午夜電影在線免費 瀏覽:224
大數據filetypepdf 瀏覽:8