posts - 5,  comments - 7,  trackbacks - 0
          <2025年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          常用鏈接

          留言簿(2)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          jsf

          搜索

          •  

          積分與排名

          • 積分 - 56068
          • 排名 - 925

          最新評論

          閱讀排行榜

          評論排行榜

          Java解釋Excel數據(jxl.jar包的使用)

          關鍵字: java excel jxl.jar

          jxl.jar 包
          下載地址:
          http://www.andykhan.com/jexcelapi/
          真實下載地址:
          http://www.andykhan.com/jexcelapi/download.html

          網站上對它的特征有如下描述:
          ● 支持Excel 95-2000的所有版本
          ● 生成Excel 2000標準格式
          ● 支持字體、數字、日期操作
          ● 能夠修飾單元格屬性
          ● 支持圖像和圖表
          應該說以上功能已經能夠大致滿足我們的需要。最關鍵的是這套API是純Java的,并不依賴Windows系統,即使運行在Linux下,它同樣能夠正確的處理Excel文件。另外需要說明的是,這套API對圖形和圖表的支持很有限,而且僅僅識別PNG格式。
          搭建環境
          將下載后的文件解包,得到jxl.jar,放入classpath,安裝就完成了。

          基本操作

          一、創建文件
          擬生成一個名為“測試數據.xls”的Excel文件,其中第一個工作表被命名為“第一頁”,大致效果如下:

           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;    
          10import jxl.*;    
          11import jxl.write.*;    
          12  
          13/**  
          14 * @author Ken  
          15 *  
          16 * To change the template for this generated type comment go to  
          17 * Window>Preferences>Java>Code Generation>Code and Comments  
          18 */
            
          19public class CreateXLS {   
          20  
          21    public static void main(String[] args) {   
          22        try {   
          23            //open file.   
          24            WritableWorkbook book = Workbook.createWorkbook(new File("d:/Test.xls"));   
          25               
          26            //create Sheet named "Sheet_1". 0 means this is 1st page.   
          27            WritableSheet sheet = book.createSheet("Sheet_1"0);   
          28               
          29            //define cell column and row in Label Constructor, and cell content write "test".   
          30            //cell is 1st-Column,1st-Row. value is "test".   
          31            Label label = new Label(00"test");   
          32            //add defined cell above to sheet instance.   
          33            sheet.addCell(label);   
          34               
          35            //create cell using add numeric. WARN:necessarily use integrated package-path, otherwise will be throws path-error.   
          36            //cell is 2nd-Column, 1st-Row. value is 789.123.   
          37            jxl.write.Number number = new jxl.write.Number(10789.123);   
          38            //add defined cell above to sheet instance.   
          39            sheet.addCell(number);   
          40               
          41            //add defined all cell above to case.   
          42            book.write();   
          43            //close file case.   
          44            book.close();   
          45        }
           catch (Exception e) {   
          46            e.printStackTrace();   
          47        }
             
          48    }
             
          49}
            
          50

           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;    
          10import jxl.*;    
          11import jxl.write.*;    
          12  
          13/**  
          14 * @author Ken  
          15 *  
          16 * To change the template for this generated type comment go to  
          17 * Window>Preferences>Java>Code Generation>Code and Comments  
          18 */
            
          19public class CreateXLS {   
          20  
          21    public static void main(String[] args) {   
          22        try {   
          23            //open file.   
          24            WritableWorkbook book = Workbook.createWorkbook(new File("d:/Test.xls"));   
          25               
          26            //create Sheet named "Sheet_1". 0 means this is 1st page.   
          27            WritableSheet sheet = book.createSheet("Sheet_1"0);   
          28               
          29            //define cell column and row in Label Constructor, and cell content write "test".   
          30            //cell is 1st-Column,1st-Row. value is "test".   
          31            Label label = new Label(00"test");   
          32            //add defined cell above to sheet instance.   
          33            sheet.addCell(label);   
          34               
          35            //create cell using add numeric. WARN:necessarily use integrated package-path, otherwise will be throws path-error.   
          36            //cell is 2nd-Column, 1st-Row. value is 789.123.   
          37            jxl.write.Number number = new jxl.write.Number(10789.123);   
          38            //add defined cell above to sheet instance.   
          39            sheet.addCell(number);   
          40               
          41            //add defined all cell above to case.   
          42            book.write();   
          43            //close file case.   
          44            book.close();   
          45        }
           catch (Exception e) {   
          46            e.printStackTrace();   
          47        }
             
          48    }
             
          49}
            
          50

          編譯執行后,會在當前位置產生一個Excel文件。

          二、讀取文件
          以剛才我們創建的Excel文件為例,做一個簡單的讀取操作,程序代碼如下:
           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;   
          10import jxl.*;   
          11  
          12/**  
          13 * @author Ken  
          14 *  
          15 * To change the template for this generated type comment go to  
          16 * Window>Preferences>Java>Code Generation>Code and Comments  
          17 */
            
          18public class ReadXLS {   
          19  
          20    public static void main(String[] args) {   
          21        try {   
          22            Workbook book = Workbook.getWorkbook(new File("d:/Test.xls"));   
          23            //get a Sheet object.    
          24            Sheet sheet = book.getSheet(0);   
          25            //get 1st-Column,1st-Row content.   
          26            Cell cell = sheet.getCell(00);   
          27            String result = cell.getContents();   
          28            System.out.println(result);   
          29            book.close();   
          30        }
           catch (Exception e) {   
          31            e.printStackTrace();   
          32        }
             
          33  
          34    }
             
          35}
            

           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;   
          10import jxl.*;   
          11  
          12/**  
          13 * @author Ken  
          14 *  
          15 * To change the template for this generated type comment go to  
          16 * Window>Preferences>Java>Code Generation>Code and Comments  
          17 */
            
          18public class ReadXLS {   
          19  
          20    public static void main(String[] args) {   
          21        try {   
          22            Workbook book = Workbook.getWorkbook(new File("d:/Test.xls"));   
          23            //get a Sheet object.    
          24            Sheet sheet = book.getSheet(0);   
          25            //get 1st-Column,1st-Row content.   
          26            Cell cell = sheet.getCell(00);   
          27            String result = cell.getContents();   
          28            System.out.println(result);   
          29            book.close();   
          30        }
           catch (Exception e) {   
          31            e.printStackTrace();   
          32        }
             
          33  
          34    }
             
          35}
            
          36

          程序執行結果:test

          三、修改文件
          利用jExcelAPI可以修改已有的Excel文件,修改Excel文件的時候,除了打開文件的方式不同之外,其他操作和創建Excel是一樣的。下面的例子是在我們已經生成的Excel文件中添加一個工作表:
          修改Excel的類,添加一個工作表
           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;   
          10import jxl.*;   
          11import jxl.write.*;   
          12  
          13/**  
          14 * @author Ken  
          15 *  
          16 * To change the template for this generated type comment go to  
          17 * Window>Preferences>Java>Code Generation>Code and Comments  
          18 */
            
          19public class UpdateXLS {   
          20  
          21    public static void main(String[] args) {   
          22        try {   
          23            //get file.   
          24            Workbook wb = Workbook.getWorkbook(new File("d:/Test.xls"));   
          25            //open a copy file(new file), then write content with same content with Test.xls.     
          26            WritableWorkbook book =   
          27                Workbook.createWorkbook(new File("d:/Test.xls"), wb);   
          28            //add a Sheet.   
          29            WritableSheet sheet = book.createSheet("Sheet_2"1);   
          30            sheet.addCell(new Label(00"test2"));   
          31            book.write();   
          32            book.close();   
          33        }
           catch (Exception e) {   
          34            e.printStackTrace();   
          35        }
             
          36    }
             
          37}
            

           1/*  
           2 * Created on Dec 30, 2007  
           3 *  
           4 * To change the template for this generated file go to  
           5 * Window>Preferences>Java>Code Generation>Code and Comments  
           6 */
            
           7package JExcelTest.standard;   
           8  
           9import java.io.*;   
          10import jxl.*;   
          11import jxl.write.*;   
          12  
          13/**  
          14 * @author Ken  
          15 *  
          16 * To change the template for this generated type comment go to  
          17 * Window>Preferences>Java>Code Generation>Code and Comments  
          18 */
            
          19public class UpdateXLS {   
          20  
          21    public static void main(String[] args) {   
          22        try {   
          23            //get file.   
          24            Workbook wb = Workbook.getWorkbook(new File("d:/Test.xls"));   
          25            //open a copy file(new file), then write content with same content with Test.xls.     
          26            WritableWorkbook book =   
          27                Workbook.createWorkbook(new File("d:/Test.xls"), wb);   
          28            //add a Sheet.   
          29            WritableSheet sheet = book.createSheet("Sheet_2"1);   
          30            sheet.addCell(new Label(00"test2"));   
          31            book.write();   
          32            book.close();   
          33        }
           catch (Exception e) {   
          34            e.printStackTrace();   
          35        }
             
          36    }
             
          37}
            
          38

          高級操作

          一、 數據格式化
          在Excel中不涉及復雜的數據類型,能夠比較好的處理字串、數字和日期已經能夠滿足一般的應用。
          字串格式化
          字符串的格式化涉及到的是字體、粗細、字號等元素,這些功能主要由WritableFont和WritableCellFormat類來負責。假設我們在生成一個含有字串的單元格時,使用如下語句,為方便敘述,我們為每一行命令加了編號:
          WritableFont font1= new WritableFont(WritableFont.TIMES,16,WritableFont.BOLD);

          //設置字體格式為excel支持的格式
          WritableFont font3=new WritableFont(WritableFont.createFont("楷體_GB2312"),12,WritableFont.NO_BOLD );
          ① WritableCellFormat format1=new WritableCellFormat(font1);
          ② Label label=new Label(0,0,”data 4 test”,format1)
          ③ 其中
          I.指定了字串格式:字體為TIMES,字號16,加粗顯示。WritableFont有非常豐富的構造子,供不同情況下使用,jExcelAPI的java-doc中有詳細列表,這里不再列出。
          II.處代碼使用了WritableCellFormat類,這個類非常重要,通過它可以指定單元格的各種屬性,后面的單元格格式化中會有更多描述。
          III.處使用了Label類的構造子,指定了字串被賦予那種格式。 在WritableCellFormat類中,還有一個很重要的方法是指定數據的對齊方式,比如針對我們上面的實例,可以指定:
          //把水平對齊方式指定為居中
          format1.setAlignment(jxl.format.Alignment.CENTRE);
          //把垂直對齊方式指定為居中
          format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
          //設置自動換行
          format1.setWrap(true);

          二、單元格操作
          Excel中很重要的一部分是對單元格的操作,比如行高、列寬、單元格合并等,所幸jExcelAPI提供了這些支持。這些操作相對比較簡單,下面只介紹一下相關的API。
          1、 合并單元格
          WritableSheet.mergeCells(int m,int n,int p,int q);
          作用是從(m,n)到(p,q)的單元格全部合并,比如:
          WritableSheet sheet=book.createSheet(“第一頁”,0);
          //合并第一列第一行到第六列第一行的所有單元格
          sheet.mergeCells(0,0,5,0);
          合并既可以是橫向的,也可以是縱向的。合并后的單元格不能再次進行合并,否則會觸發異常。
          2、 行高和列寬
          WritableSheet.setRowView(int i,int height);
          作用是指定第i+1行的高度,比如:
          //將第一行的高度設為200
          sheet.setRowView(0,200);
          WritableSheet.setColumnView(int i,int width);
          作用是指定第i+1列的寬度,比如:
          //將第一列的寬度設為30
          sheet.setColumnView(0,30);
          三、操作圖片
          1public static void write()throws Exception{   
          2        WritableWorkbook wwb=Workbook.createWorkbook(new File("c:/1.xls"));   
          3        WritableSheet ws=wwb.createSheet("Test Sheet 1",0);   
          4        File file=new File("C:\\jbproject\\PVS\\WebRoot\\weekhit\\1109496996281.png");   
          5        WritableImage image=new WritableImage(14618,file);   
          6        ws.addImage(image);   
          7        wwb.write();   
          8        wwb.close();   
          9    }
            

          1public static void write()throws Exception{   
          2        WritableWorkbook wwb=Workbook.createWorkbook(new File("c:/1.xls"));   
          3        WritableSheet ws=wwb.createSheet("Test Sheet 1",0);   
          4        File file=new File("C:\\jbproject\\PVS\\WebRoot\\weekhit\\1109496996281.png");   
          5        WritableImage image=new WritableImage(14618,file);   
          6        ws.addImage(image);   
          7        wwb.write();   
          8        wwb.close();   
          9    }
            

          很簡單和插入單元格的方式一樣,不過就是參數多了些,WritableImage這個類繼承了Draw,上面只是他構造方法的一種,最后一個參數不用了說了,前面四個參數的類型都是double,依次是 x, y, width, height,注意,這里的寬和高可不是圖片的寬和高,而是圖片所要占的單位格的個數,因為繼承的Draw所以他的類型必須是double,具體里面怎么實現的我還沒細看:)因為著急趕活,先完成功能,其他的以后有時間慢慢研究。以后會繼續寫出在使用中的心得給大家。

          讀:
          讀的時候是這樣的一個思路,先用一個輸入流(InputStream)得到Excel文件,然后用jxl中的Workbook得到工作薄,用Sheet從工作薄中得到工作表,用Cell得到工作表中得某個單元格.
          InputStream->Workbook->Sheet->Cell,就得到了excel文件中的單元格
          1String path="c:\\excel.xls";//Excel文件URL   
          2InputStream is = new FileInputStream(path);//寫入到FileInputStream   
          3jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄    
          4jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一個工作表   
          5Cell cell=st.getCell(0,0);//得到工作表的第一個單元格,即A1   
          6String content=cell.getContents();//getContents()將Cell中的字符轉為字符串   
          7wb.close();//關閉工作薄   
          8is.close();//關閉輸入流  
          9

          1String path="c:\\excel.xls";//Excel文件URL   
          2InputStream is = new FileInputStream(path);//寫入到FileInputStream   
          3jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄    
          4jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一個工作表   
          5Cell cell=st.getCell(0,0);//得到工作表的第一個單元格,即A1   
          6String content=cell.getContents();//getContents()將Cell中的字符轉為字符串   
          7wb.close();//關閉工作薄   
          8is.close();//關閉輸入流 

          我們可以通過Sheet的getCell(x,y)方法得到任意一個單元格,x,y和excel中的坐標對應.
          例如A1對應(0,0),A2對應(0,1),D3對應(3,2).Excel中坐標從A,1開始,jxl中全部是從0開始.
          還可以通過Sheet的getRows(),getColumns()方法得到行數列數,并用于循環控制,輸出一個sheet中的所有內容.

          寫:
          往Excel中寫入內容主要是用jxl.write包中的類.
          思路是這樣的:
          OutputStream<-WritableWorkbook<-WritableSheet<-Label
          這里面Label代表的是寫入Sheet的Cell位置及內容.
           1OutputStream os=new FileOutputStream("c:\\test.xls");//輸出的Excel文件URL   
           2WritableWorkbook wwb = Workbook.createWorkbook(os);//創建可寫工作薄   
           3WritableSheet ws = wwb.createSheet("sheet1"0);//創建可寫工作表   
           4Label labelCF=new Label(00"hello");//創建寫入位置和內容   
           5ws.addCell(labelCF);//將Label寫入sheet中   
           6Label的構造函數Label(int x, int y,String aString)xy意同讀的時候的xy,aString是寫入的內容.   
           7WritableFont wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);//設置寫入字體   
           8WritableCellFormat wcfF = new WritableCellFormat(wf);//設置CellFormat   
           9Label labelCF=new Label(00"hello");//創建寫入位置,內容和格式   
          10Label的另一構造函數Label(int c, int r, String cont, CellFormat st)可以對寫入內容進行格式化,設置字體及其它的屬性.   
          11現在可以寫了   
          12wwb.write();   
          13寫完后關閉   
          14wwb.close();   
          15輸出流也關閉吧   
          16os.close;  

           1OutputStream os=new FileOutputStream("c:\\test.xls");//輸出的Excel文件URL   
           2WritableWorkbook wwb = Workbook.createWorkbook(os);//創建可寫工作薄   
           3WritableSheet ws = wwb.createSheet("sheet1"0);//創建可寫工作表   
           4Label labelCF=new Label(00"hello");//創建寫入位置和內容   
           5ws.addCell(labelCF);//將Label寫入sheet中   
           6Label的構造函數Label(int x, int y,String aString)xy意同讀的時候的xy,aString是寫入的內容.   
           7WritableFont wf = new WritableFont(WritableFont.TIMES, 12, WritableFont.BOLD, false);//設置寫入字體   
           8WritableCellFormat wcfF = new WritableCellFormat(wf);//設置CellFormat   
           9Label labelCF=new Label(00"hello");//創建寫入位置,內容和格式   
          10Label的另一構造函數Label(int c, int r, String cont, CellFormat st)可以對寫入內容進行格式化,設置字體及其它的屬性.   
          11現在可以寫了   
          12wwb.write();   
          13寫完后關閉   
          14wwb.close();   
          15輸出流也關閉吧   
          16os.close; 

          OK,只要把讀和寫結合起來,就可以在N個Excel中讀取數據寫入你希望的Excel新表中,還是比較方便的.

          下面是程序一例:
           1sql = "select * from tablename";   
           2rs = stmt.executeQuery(sql);   
           3  
           4//新建Excel文件   
           5String filePath=request.getRealPath("aaa.xls");   
           6File myFilePath=new File(filePath);   
           7if(!myFilePath.exists())   
           8myFilePath.createNewFile();   
           9FileWriter resultFile=new FileWriter(myFilePath);   
          10PrintWriter myFile=new PrintWriter(resultFile);   
          11resultFile.close();   
          12  
          13        //用JXL向新建的文件中添加內容   
          14    OutputStream outf = new FileOutputStream(filePath);   
          15        jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(outf);   
          16        jxl.write.WritableSheet ws = wwb.createSheet("sheettest"0);   
          17  
          18int i=0;   
          19        int j=0;   
          20  
          21for (int k = 0; k < rs.getMetaData().getColumnCount(); k++{   
          22    ws.addCell(new Label(k,0,rs.getMetaData().getColumnName(k+1)));   
          23}
             
          24  
          25while(rs.next()){   
          26    out.println(rs.getMetaData().getColumnCount());   
          27  
          28for (int k = 0; k < rs.getMetaData().getColumnCount(); k++{   
          29ws.addCell(new Label(k,j+i+1,rs.getString(k+1)));   
          30    }
               
          31  
          32 i++;   
          33}
             
          34wwb.write();   
          35    wwb.close();   
          36}catch(Exception e){e.printStackTrace();}   
          37finally{   
          38  
          39rs.close();   
          40conn.close();   
          41}
             
          42  
          43response.sendRedirect("aaa.xls"); 
          posted on 2008-11-25 13:08 Vincent-chen 閱讀(2316) 評論(0)  編輯  收藏 所屬分類: PrintJXL
          主站蜘蛛池模板: 涿州市| 全州县| 茌平县| 岗巴县| 博客| 江川县| 肃宁县| 许昌县| 沾益县| 泽普县| 东乌珠穆沁旗| 资兴市| 隆德县| 岳池县| 丽江市| 自治县| 太原市| 凌海市| 阿坝| 巩留县| 九龙坡区| 广东省| 长丰县| 乌兰浩特市| 隆化县| 天等县| 内丘县| 巫山县| 孟连| 汉寿县| 通海县| 巴彦淖尔市| 大渡口区| 五台县| 柳江县| 黔西县| 交口县| 泗洪县| 远安县| 钟祥市| 乐业县|