隨筆 - 40, 文章 - 0, 評論 - 20, 引用 - 0
          數(shù)據(jù)加載中……

          Java Excel 使用攻略

           現(xiàn)在正在做的項目中涉及大量的Excel文件導出導入操作,都是使用Java Excel來操作。

          Java Excel是一開放源碼項目,通過它Java開發(fā)人員可以讀取Excel文件的內(nèi)容、創(chuàng)建新的Excel文件、更新已經(jīng)存在的Excel文件。下面我寫了一個簡單的例子,展示基本的讀取,新建,更新(包括常見格式的設(shè)置:字體,顏色,背景,合并單元格),拷貝操作,有這些其實已經(jīng)基本足夠應(yīng)付大部分問題了。下面是例的源代碼:

          import java.io.*;
          import java.util.Date;

          import jxl.*;
          import jxl.format.Colour;
          import jxl.format.UnderlineStyle;
          import jxl.read.biff.BiffException;
          import jxl.write.*;
          import jxl.format.UnderlineStyle;
          import jxl.format.CellFormat;;

          public class OperateExcel {
           
           /**
            * Read data from a excel file
            */
           public static void  readExcel(String excelFileName){
            Workbook  rwb = null;  
            try{
             InputStream stream = new FileInputStream(excelFileName);
             rwb = Workbook.getWorkbook(stream);
             Sheet  sheet = rwb.getSheet(0);
             Cell   cell  = null;
             int columns = sheet.getColumns();
             int rows    = sheet.getRows();
             for( int i=0 ; i< rows ; i++ )
              for( int j=0 ; j< columns ; j++){
               //attention: The first parameter is column,the second parameter is row.  
               cell = sheet.getCell(j,i);    
               String str00 = cell.getContents();
               if( cell.getType() == CellType.LABEL )
                 str00 += " LAEBL";
               else if( cell.getType() == CellType.NUMBER)
                 str00 += " number";
               else if( cell.getType() == CellType.DATE)
                 str00 += " date"; 
               System.out.println("00==>"+str00);
              } 
             stream.close();
            }
            catch(IOException e){  
             e.printStackTrace();
            }
            catch(BiffException e){
             e.printStackTrace();
            } 
            finally{  
             rwb.close();
            }
           }
           /**
            * create a new excelFile
            * @param excelFileName create name
            */
           public static void createExcelFile(String excelFileName){
            try{
             WritableWorkbook wwb = Workbook.createWorkbook(new File(excelFileName));
             WritableSheet     ws  = wwb.createSheet("sheet1",0);
             //also,The first parameter is  column,the second parameter is row.
             // add normal label data
             Label label00 = new Label(0,0,"Label00");
             ws.addCell(label00);
             //add font formating data   
             WritableFont  wf = new WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD , true);
             WritableCellFormat wff = new WritableCellFormat(wf);
             Label label10 = new Label(1,0,"Label10",wff);
             ws.addCell(label10);
             //add color font formating data
             WritableFont wf_color = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.RED);
             WritableCellFormat wff_color = new WritableCellFormat(wf_color);
             wff_color.setBackground(Colour.GRAY_25); //set background coloe to gray  
             Label label20 = new Label(2,0,"Label20",wff_color);   
             ws.addCell(label20);
             
             //合并單元格
             WritableFont wf_merge = new WritableFont(WritableFont.ARIAL,10,WritableFont.NO_BOLD,false,UnderlineStyle.DOUBLE_ACCOUNTING,Colour.GREEN);
             WritableCellFormat wff_merge = new WritableCellFormat(wf_merge);
             wff_merge.setBackground(Colour.BLACK);
             Label label30 = new Label(3,0,"Label30",wff_merge);   
             ws.addCell(label30);
             Label label40 = new Label(4,0,"Label40");
             ws.addCell(label40);
             Label label50 = new Label(5,0,"Label50");
             ws.addCell(label50);
               //合并 (0,3) (4,0)
               //attention : 如果合并后面的列不為空,那么就把后面格的內(nèi)容清空,格式也是按前一個單元格的格式
             ws.mergeCells(3,0,4,0);
             
             //添加Number格式數(shù)據(jù)
             jxl.write.Number labelN = new jxl.write.Number(0, 1, 3.1415926);
             ws.addCell(labelN);
             
             //添加帶有formatting的Number對象
             jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
             jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
             jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN);
             ws.addCell(labelNF);
             
             //添加Boolean對象
             jxl.write.Boolean labelBoolean = new jxl.write.Boolean(2,1,false);
             ws.addCell(labelBoolean);
             
             //添加DateTime對象
             DateTime labelDT = new DateTime(3,1,new Date());
             ws.addCell(labelDT);
             
             //添加帶有格式的DataTime數(shù)據(jù)
             DateFormat dtf = new DateFormat("yyyy-MM-dd hh:mm:ss");
             WritableCellFormat wcfDt = new WritableCellFormat(dtf);   
             wcfDt.setBackground(Colour.YELLOW);
             DateTime labelDT_format =  new DateTime(4,1,new java.util.Date(),wcfDt);
             ws.addCell(labelDT_format);
             ws.mergeCells(4,1,5,1); //比較長,用兩列來顯示     
             
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            }  
           }
           /**
            * 如何更新Excel文件
            * @param fileName
            */
           public static void updateExcel(String fileName){  
            try{
             jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(fileName));
             WritableWorkbook wwb = Workbook.createWorkbook(new File(fileName),rw);
             //這里其實執(zhí)行的是一次copy操作,把文件先讀到內(nèi)存中,修改后再保存覆蓋原來的文件來實現(xiàn)update操作
             WritableSheet ws  = wwb.getSheet(0);
             WritableCell wc = ws.getWritableCell(0,0);
             if( wc.getType() == CellType.LABEL){
              Label l = (Label)wc;
              l.setString(wc.getContents()+"_new");
             }
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            } 
            catch(BiffException e){
             e.printStackTrace();
            }
           }
           /**
            * 如何copy Excel文件
            * @param fileName
            */
           public static void copyExcel(String sourFileName,String destFileName){  
            try{
             jxl.Workbook rw = jxl.Workbook.getWorkbook(new File(sourFileName));
             WritableWorkbook wwb = Workbook.createWorkbook(new File(destFileName),rw);
             wwb.write();
             wwb.close();
            }
            catch(IOException e){
             e.printStackTrace();
            }
            catch(WriteException e){
             e.printStackTrace();
            } 
            catch(BiffException e){
             e.printStackTrace();
            }
           }
           
           public static void main(String [] argv){
            //OperateExcel.readExcel("E:\\test.xls");
            //OperateExcel.createExcelFile("E:\\test1.xls");
            //OperateExcel.updateExcel("E:\\test.xls");
            OperateExcel.copyExcel("E:\\test.xls","E:\\moon.xls");
           }

          }


          posted on 2005-12-06 15:06 月亮 閱讀(2202) 評論(4)  編輯  收藏

          評論

          # re: Java Excel 使用攻略  回復  更多評論   

          有沒有人對Java Excel和apache的開源項目:POI(http://jakarta.apache.org/poi/index.html)做個比較呢?
          2005-12-07 09:27 | 文軸

          # re: Java Excel 使用攻略  回復  更多評論   

          POI功能更復雜
          在內(nèi)存占用和效率方面,jxl高出poi很多
          2005-12-09 17:10 | ptrx

          # re: Java Excel 使用攻略  回復  更多評論   

          E:\\test1.xls
          這里生成的文件的路徑都是寫死了的,怎么樣能動態(tài)生成文件的路徑啊?例如我做的是web開發(fā),打包后放到不同的路徑后,該文件的位置后自動找到啊?能說說嗎?我找了很久多不知道怎么做,只知道有人用ClassLoader來做,但我不會用
          2005-12-30 00:05 | 游客

          # re: Java Excel 使用攻略  回復  更多評論   

          舉個例子,我用的web服務(wù)器是weblogic,我在服務(wù)器的config\excelOutport目錄里面放上了我想要的Excel文件,整個目錄名為:
          D:\bea\user_projects\domains\mydomainc\myserver\config\excelOutport
          那么我要在servlet中得到這個路徑,可以這么寫:
          String filePath = System.getProperty("user.dir");
          filePath += System.getProperty("file.separator");
          filePath += System.getProperty("weblogic.Name");
          filePath += System.getProperty("file.separator");
          filePath += "config";
          filePath += System.getProperty("file.separator");
          filePath += "excelOutport";
          filePath += System.getProperty("file.separator");
          filePath += "test.xls";
          其他的服務(wù)器應(yīng)該也有相似的辦法,你試一下。
          2005-12-31 17:58 | 月亮

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 霍邱县| 彩票| 三江| 屏东市| 孟州市| 新源县| 临城县| 社会| 巍山| 屏东县| 凤翔县| 天峨县| 永福县| 抚松县| 泾源县| 邛崃市| 华安县| 澜沧| 临清市| 怀柔区| 松滋市| 灯塔市| 洪江市| 尚义县| 池州市| 洛浦县| 乌拉特中旗| 海安县| 政和县| 赤壁市| 祥云县| 嘉义县| SHOW| 陵川县| 新民市| 定边县| 巴青县| 临邑县| 明光市| 嘉定区| 青田县|