`

java Excel 操作例子

阅读更多
   1. package excel.jxl;  
   2.   
   3. import java.io.File;  
   4. import java.io.FileOutputStream;  
   5. import java.io.OutputStream;  
   6. import java.util.ArrayList;  
   7. import java.util.Date;  
   8.   
   9. import jxl.Cell;  
  10. import jxl.CellType;  
  11. import jxl.Sheet;  
  12. import jxl.Workbook;  
  13. import jxl.WorkbookSettings;  
  14. import jxl.format.Alignment;  
  15. import jxl.format.Border;  
  16. import jxl.format.BorderLineStyle;  
  17. import jxl.format.Colour;  
  18. import jxl.format.VerticalAlignment;  
  19. import jxl.write.Formula;  
  20. import jxl.write.Label;  
  21. import jxl.write.NumberFormat;  
  22. import jxl.write.WritableCellFeatures;  
  23. import jxl.write.WritableCellFormat;  
  24. import jxl.write.WritableFont;  
  25. import jxl.write.WritableSheet;  
  26. import jxl.write.WritableWorkbook;  
  27. import jxl.write.WriteException;  
  28.   
  29. public class JExcelUtils {  
  30.   
  31.     /** 
  32.      * 生成Excel文件 
  33.      * @param path         文件路径 
  34.      * @param sheetName    工作表名称 
  35.      * @param dataTitles   数据标题 
  36.      */  
  37.    public void createExcelFile(String path,String sheetName,String[] dataTitles){  
  38.        WritableWorkbook workbook;  
  39.        try{  
  40.            OutputStream os=new FileOutputStream(path);   
  41.            workbook=Workbook.createWorkbook(os);   
  42.   
  43.            WritableSheet sheet = workbook.createSheet(sheetName, 0); //添加第一个工作表  
  44.            initialSheetSetting(sheet);  
  45.              
  46.            Label label;  
  47.            for (int i=0; i<dataTitles.length; i++){  
  48.                //Label(列号,行号,内容,风格)  
  49.                label = new Label(i, 0, dataTitles[i],getTitleCellFormat());   
  50.                sheet.addCell(label);   
  51.            }  
  52.   
  53.            //插入一行  
  54.            insertRowData(sheet,1,new String[]{"200201001","张三","100","60","100","260"},getDataCellFormat(CellType.STRING_FORMULA));  
  55.              
  56.            //一个一个插入行  
  57.            label = new Label(0, 2,"200201002",getDataCellFormat(CellType.STRING_FORMULA));   
  58.            sheet.addCell(label);  
  59.              
  60.            label = new Label(1, 2,"李四",getDataCellFormat(CellType.STRING_FORMULA));   
  61.            sheet.addCell(label);  
  62.              
  63.            insertOneCellData(sheet,2,2,70.5,getDataCellFormat(CellType.NUMBER));  
  64.            insertOneCellData(sheet,3,2,90.523,getDataCellFormat(CellType.NUMBER));  
  65.            insertOneCellData(sheet,4,2,60.5,getDataCellFormat(CellType.NUMBER));  
  66.   
  67.            insertFormula(sheet,5,2,"C3+D3+E3",getDataCellFormat(CellType.NUMBER_FORMULA));  
  68.              
  69.            //插入日期  
  70.            mergeCellsAndInsertData(sheet, 0, 3, 5, 3, new Date(), getDataCellFormat(CellType.DATE));  
  71.              
  72.            workbook.write();   
  73.            workbook.close();  
  74.        }catch(Exception e){  
  75.            e.printStackTrace();  
  76.        }  
  77.    }  
  78.      
  79.    /** 
  80.     * 初始化表格属性 
  81.     * @param sheet 
  82.     */  
  83.    public void initialSheetSetting(WritableSheet sheet){  
  84.       try{  
  85.            //sheet.getSettings().setProtected(true); //设置xls的保护,单元格为只读的  
  86.            sheet.getSettings().setDefaultColumnWidth(10); //设置列的默认宽度  
  87.            //sheet.setRowView(2,false);//行高自动扩展   
  88.            //setRowView(int row, int height);--行高   
  89.            //setColumnView(int  col,int width); --列宽  
  90.            sheet.setColumnView(0,20);//设置第一列宽度  
  91.       }catch(Exception e){  
  92.           e.printStackTrace();  
  93.       }  
  94.    }  
  95.      
  96.    /** 
  97.     * 插入公式 
  98.     * @param sheet 
  99.     * @param col 
 100.     * @param row 
 101.     * @param formula 
 102.     * @param format 
 103.     */  
 104.    public void insertFormula(WritableSheet sheet,Integer col,Integer row,String formula,WritableCellFormat format){  
 105.        try{  
 106.            Formula f = new Formula(col, row, formula, format);  
 107.            sheet.addCell(f);  
 108.        }catch(Exception e){  
 109.            e.printStackTrace();  
 110.        }  
 111.    }  
 112.      
 113.    /** 
 114.     * 插入一行数据 
 115.     * @param sheet       工作表 
 116.     * @param row         行号 
 117.     * @param content     内容 
 118.     * @param format      风格 
 119.     */  
 120.    public void insertRowData(WritableSheet sheet,Integer row,String[] dataArr,WritableCellFormat format){  
 121.        try{  
 122.            Label label;  
 123.            for(int i=0;i<dataArr.length;i++){  
 124.                label = new Label(i,row,dataArr[i],format);  
 125.                sheet.addCell(label);  
 126.            }  
 127.        }catch(Exception e){  
 128.            e.printStackTrace();  
 129.        }  
 130.    }  
 131.      
 132.    /** 
 133.     * 插入单元格数据 
 134.     * @param sheet 
 135.     * @param col 
 136.     * @param row 
 137.     * @param data 
 138.     */  
 139.    public void insertOneCellData(WritableSheet sheet,Integer col,Integer row,Object data,WritableCellFormat format){  
 140.        try{  
 141.            if(data instanceof Double){  
 142.                jxl.write.Number  labelNF = new jxl.write.Number(col,row,(Double)data,format);   
 143.                sheet.addCell(labelNF);   
 144.            }else if(data instanceof Boolean){  
 145.                jxl.write.Boolean labelB = new jxl.write.Boolean(col,row,(Boolean)data,format);   
 146.                sheet.addCell(labelB);   
 147.            }else if(data instanceof Date){  
 148.                jxl.write.DateTime labelDT = new jxl.write.DateTime(col,row,(Date)data,format);   
 149.                sheet.addCell(labelDT);   
 150.                setCellComments(labelDT, "这是个创建表的日期说明!");  
 151.            }else{  
 152.                Label label = new Label(col,row,data.toString(),format);  
 153.                sheet.addCell(label);                 
 154.            }  
 155.        }catch(Exception e){  
 156.            e.printStackTrace();  
 157.        }  
 158.   
 159.   }  
 160.      
 161.    /** 
 162.     * 合并单元格,并插入数据 
 163.     * @param sheet 
 164.     * @param col_start 
 165.     * @param row_start 
 166.     * @param col_end 
 167.     * @param row_end 
 168.     * @param data 
 169.     * @param format 
 170.     */  
 171.    public void mergeCellsAndInsertData(WritableSheet sheet,Integer col_start,Integer row_start,Integer col_end,Integer row_end,Object data, WritableCellFormat format){  
 172.       try{  
 173.           sheet.mergeCells(col_start,row_start,col_end,row_end);//左上角到右下角  
 174.           insertOneCellData(sheet, col_start, row_start, data, format);  
 175.       }catch(Exception e){  
 176.           e.printStackTrace();  
 177.       }  
 178.   
 179.    }  
 180.      
 181.    /** 
 182.     * 给单元格加注释 
 183.     * @param label 
 184.     * @param comments 
 185.     */  
 186.    public void setCellComments(Object label,String comments){  
 187.        WritableCellFeatures cellFeatures = new WritableCellFeatures();  
 188.        cellFeatures.setComment(comments);  
 189.        if(label instanceof jxl.write.Number){  
 190.            jxl.write.Number num = (jxl.write.Number)label;  
 191.            num.setCellFeatures(cellFeatures);  
 192.        }else if(label instanceof jxl.write.Boolean){  
 193.            jxl.write.Boolean bool = (jxl.write.Boolean)label;  
 194.            bool.setCellFeatures(cellFeatures);  
 195.        }else if(label instanceof jxl.write.DateTime){  
 196.            jxl.write.DateTime dt = (jxl.write.DateTime)label;  
 197.            dt.setCellFeatures(cellFeatures);  
 198.        }else{  
 199.            Label _label = (Label)label;  
 200.            _label.setCellFeatures(cellFeatures);  
 201.        }  
 202.    }  
 203.      
 204.    /** 
 205.    * 读取excel 
 206.    * @param inputFile 
 207.    * @param inputFileSheetIndex 
 208.    * @throws Exception 
 209.    */  
 210.    public ArrayList<String> readDataFromExcel(File inputFile, int inputFileSheetIndex){  
 211.       ArrayList<String> list = new ArrayList<String>();  
 212.       Workbook book = null;  
 213.       Cell cell = null;  
 214.       WorkbookSettings setting = new WorkbookSettings();   
 215.       java.util.Locale locale = new java.util.Locale("zh","CN");   
 216.       setting.setLocale(locale);  
 217.       setting.setEncoding("ISO-8859-1");  
 218.       try{  
 219.           book = Workbook.getWorkbook(inputFile, setting);  
 220.       }catch(Exception e){  
 221.           e.printStackTrace();    
 222.       }  
 223.   
 224.       Sheet sheet = book.getSheet(inputFileSheetIndex);  
 225.       for (int rowIndex = 0; rowIndex < sheet.getRows(); rowIndex++) {//行  
 226.        for (int colIndex = 0; colIndex < sheet.getColumns(); colIndex++) {//列  
 227.            cell = sheet.getCell(colIndex, rowIndex);  
 228.            //System.out.println(cell.getContents());  
 229.            list.add(cell.getContents());  
 230.        }  
 231.       }  
 232.       book.close();  
 233.   
 234.       return list;  
 235.    }  
 236.   
 237.    /** 
 238.     * 得到数据表头格式 
 239.     * @return 
 240.     */  
 241.    public WritableCellFormat getTitleCellFormat(){  
 242.        WritableCellFormat wcf = null;  
 243.        try {  
 244.            //字体样式  
 245.            WritableFont wf = new WritableFont(WritableFont.TIMES,12, WritableFont.NO_BOLD,false);//最后一个为是否italic  
 246.            wf.setColour(Colour.RED);  
 247.            wcf = new WritableCellFormat(wf);  
 248.            //对齐方式  
 249.            wcf.setAlignment(Alignment.CENTRE);  
 250.            wcf.setVerticalAlignment(VerticalAlignment.CENTRE);  
 251.            //边框  
 252.            wcf.setBorder(Border.ALL,BorderLineStyle.THIN);  
 253.              
 254.            //背景色  
 255.            wcf.setBackground(Colour.GREY_25_PERCENT);  
 256.        } catch (WriteException e) {  
 257.         e.printStackTrace();  
 258.        }  
 259.        return wcf;  
 260.    }  
 261.      
 262.    /** 
 263.     * 得到数据格式 
 264.     * @return 
 265.     */  
 266.    public WritableCellFormat getDataCellFormat(CellType type){  
 267.        WritableCellFormat wcf = null;  
 268.        try {  
 269.            //字体样式  
 270.            if(type == CellType.NUMBER || type == CellType.NUMBER_FORMULA){//数字  
 271.               NumberFormat nf = new NumberFormat("#.00");  
 272.               wcf = new WritableCellFormat(nf);   
 273.            }else if(type == CellType.DATE || type == CellType.DATE_FORMULA){//日期  
 274.                jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd hh:mm:ss");   
 275.                wcf = new jxl.write.WritableCellFormat(df);   
 276.            }else{  
 277.                WritableFont wf = new WritableFont(WritableFont.TIMES,10, WritableFont.NO_BOLD,false);//最后一个为是否italic  
 278.                wcf = new WritableCellFormat(wf);  
 279.            }  
 280.            //对齐方式  
 281.            wcf.setAlignment(Alignment.CENTRE);  
 282.            wcf.setVerticalAlignment(VerticalAlignment.CENTRE);  
 283.            //边框  
 284.            wcf.setBorder(Border.LEFT,BorderLineStyle.THIN);  
 285.            wcf.setBorder(Border.BOTTOM,BorderLineStyle.THIN);  
 286.            wcf.setBorder(Border.RIGHT,BorderLineStyle.THIN);  
 287.            //背景色  
 288.            wcf.setBackground(Colour.WHITE);  
 289.              
 290.            wcf.setWrap(true);//自动换行  
 291.              
 292.        } catch (WriteException e) {  
 293.         e.printStackTrace();  
 294.        }  
 295.        return wcf;  
 296.    }  
 297.      
 298.    /** 
 299.     * 打开文件看看 
 300.     * @param exePath 
 301.     * @param filePath 
 302.     */  
 303.    public void openExcel(String exePath,String filePath){  
 304.        Runtime r=Runtime.getRuntime();   
 305.        String cmd[]={exePath,filePath};   
 306.        try{   
 307.            r.exec(cmd);   
 308.        }catch(Exception e){  
 309.            e.printStackTrace();  
 310.        }  
 311.    }  
 312.      
 313.    public static void main(String[] args){  
 314.        String[] titles = {"学号","姓名","语文","数学","英语","总分"};   
 315.        JExcelUtils jxl = new JExcelUtils();  
 316.        String filePath = "E:/test.xls";  
 317.        jxl.createExcelFile(filePath,"成绩单",titles);  
 318.        jxl.readDataFromExcel(new File(filePath),0);  
 319.        jxl.openExcel("C:/Program Files/Microsoft Office/OFFICE11/EXCEL.EXE",filePath);  
 320.    }  
 321. }  
 
分享到:
评论
1 楼 powerclark 2010-03-16  
很不错的用java读写EXCEL的例子集合。。。

相关推荐

Global site tag (gtag.js) - Google Analytics