?????? 關(guān)于word文檔操作, 網(wǎng)上不少這樣的例子,好像都是一篇文章。word文檔嵌入到網(wǎng)頁中好像比較簡單一些。加個(gè)報(bào)文頭基本上就可以實(shí)現(xiàn)此功能。而導(dǎo)出數(shù)據(jù)到word文檔中,我可費(fèi)了不少的腦細(xì)胞。閑話少說,步入正題。。。:)
????? 網(wǎng)頁中嵌入word文檔,在jsp程序開頭部分加入<%@ page contentType="application/msword;charset=GBK"%>這些代碼,即可實(shí)現(xiàn)。比較簡單,相信很多人都知道這一點(diǎn)了。
???? ?費(fèi)腦筋的是將一張報(bào)表或者一張登記表導(dǎo)入到word文檔中。報(bào)表(登記表)都是動(dòng)態(tài)生成的。那么首先的問題是如何獲得一個(gè)動(dòng)態(tài)網(wǎng)頁中的內(nèi)容。我以前使用的BufferedReader,PrintWriter,BufferedInputStream,BufferedOutputSteam都不起作用了,原因就是他們不能讀取動(dòng)態(tài)生成的網(wǎng)頁內(nèi)容。因此,我想到了URL這個(gè)類,獲得內(nèi)容的代碼如下:
????? ?java.net.URL l_url = new java.net.URL("http://localhost:9000/rlzy/employee/employee_resume.jsp?id="+emp_id);
?????? java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection();
????? ?l_connection.connect();
????? ?l_urlStream = l_connection.getInputStream();
???????java.io.BufferedReader l_reader = new java.io.BufferedReader(new java.io.InputStreamReader(l_urlStream));
?????? while ((sCurrentLine = l_reader.readLine()) != null)
??????? {
??????????content+=sCurrentLine;
???????? }?
?????? content即為我們想要得到的動(dòng)態(tài)內(nèi)容。
?????? 導(dǎo)出數(shù)據(jù)的話,使用BufferedInputStream?和?BufferedOutputStream 。但前提是把得到的動(dòng)態(tài)內(nèi)容先輸出到一個(gè)臨時(shí)的html網(wǎng)頁中,即把它先變成一個(gè)靜態(tài)文件。這樣BufferedInputStream 和BufferedOutputStream 就可以獲得要讀取和輸出的內(nèi)容。讀取完畢,再把這個(gè)臨時(shí)的html網(wǎng)頁刪除。這是網(wǎng)上流傳的代碼:
?????? BufferedInputStream bis = null;
?????? BufferedOutputStream bos = null;
?????? try {
???????????? ?bis = new BufferedInputStream(new FileInputStream(內(nèi)容資源的路徑));
????????????? bos = new BufferedOutputStream(response.getOutputStream());
???????????? ?byte[] buff = new byte[2048];
??????????? ? int bytesRead;
???????????? ?while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
??????????????bos.write(buff,0,bytesRead);
??????????? }
???????? ?} catch(final IOException e) {
??????? System.out.println ( "出現(xiàn)IOException." + e );
????????? } finally {
???????? ?if (bis != null)
??????????? bis.close();
????????? if (bos != null)
??????????? bos.close();
?????? }
?????? 此外,導(dǎo)出內(nèi)容到word文檔后,還可能會出現(xiàn)格式不正確的問題。我就遇到了html表格導(dǎo)出到word就發(fā)生變化的情況。這種情況具體原因應(yīng)該是兩種不同文件編碼的問題。我是通過修改源html文件解決的問題。至于以后如果還碰到類似問題的話,首先看一下word文檔和html文檔是從哪個(gè)地方格式開始變化了,找到之后再對癥下藥。如果你覺得這種解決方法沒什么技術(shù)含量的話,你可以根據(jù)內(nèi)容手動(dòng)輸出。。。哈
????????????????????????????????????????????????? ? 。。。。。。。。。。。學(xué)到了一些東西。。。。。。。。。。。。