2020国产成人精品视频,性做久久久久久久久,亚洲国产成人久久综合一区,亚洲影院天堂中文av色

分享

java應(yīng)用集錦3:正則表達(dá)式 excel操作之jxl (轉(zhuǎn))

 臨風(fēng)笛 2010-07-14

最近項(xiàng)目開(kāi)發(fā)中對(duì)excel操作比較頻繁,并結(jié)合正則表達(dá)式進(jìn)行了一些處理,整理一下.


1.正則表達(dá)式常用方法

Java代碼 復(fù)制代碼
  1. /**  
  2.      * 在第一個(gè)字符串中查找匹配字符串的個(gè)數(shù)  
  3.      * @param str    
  4.      * @param regexStr  
  5.      * @return  
  6.      */  
  7.     public static int count(String str,String regexStr){   
  8.         int count = 0;   
  9.         Pattern pt = Pattern.compile(regexStr);   
  10.         Matcher m = pt.matcher(str);   
  11.         int start = 0;   
  12.         while(m.find()){   
  13.             count++;   
  14.             str = str.replaceFirst(regexStr, "");   
  15.         }   
  16.         return count;   
  17.     }   
  18.   
  19. /**  
  20.      * 根據(jù)正則表達(dá)式分割str字符串成為一個(gè)一個(gè)的小的單元!  
  21.          * (實(shí)際使用:在一個(gè)類(lèi)似語(yǔ)法分析的模塊中發(fā)揮重要作用)  
  22.      * 例如:3+5*4  根據(jù)正則表達(dá)式+-\*  分割成數(shù)組  3,+,5,*,4    
  23.      * @param str  
  24.      * @param regexStr  
  25.      * @return  
  26.      */  
  27.     public static List splitByStr(String str,String regexStr){   
  28.         List temp = new ArrayList();   
  29.         Pattern pt = Pattern.compile(regexStr);   
  30.         Matcher m = pt.matcher(str);   
  31.         int start = 0;   
  32.         while(m.find()){   
  33.             //去掉下面的字符串中為空串的情況!   
  34.             if(m.start()!=start)   
  35.                 temp.add(str.substring(start, m.start()));   
  36.             temp.add(str.substring(m.start(),m.end()));   
  37.             start = m.end();   
  38.         }   
  39.         temp.add(str.substring(start));   
  40.         return temp;   
  41.     }   
  42.   
  43.       /**  
  44.      * 檢查是否含有指定的正則表達(dá)式匹配的子串.  
  45.      * @param str 目標(biāo)字符串  
  46.      * @param regex 正則表達(dá)式,如果正則表達(dá)式含有"^......$"就是查找整個(gè)字符串對(duì)象是否符合正則表達(dá)式.  
  47.      * @return  
  48.      */  
  49.     public static boolean checkInclude(String str,String regex){   
  50.          Pattern pattern = Pattern.compile(regex);   
  51.          Matcher matcher = null;   
  52.          matcher = pattern.matcher(str);   
  53.          return matcher.find();   
  54.     }   
  55.            
  56.     /**  
  57.      * 方法字符串中符合正則表達(dá)式的子串的集合.  
  58.      * @param str  
  59.      * @param regex  
  60.      * @return  
  61.      */  
  62.     public static List getRightSubStr(String str, String regex) {   
  63.         List ans = new ArrayList();   
  64.         Pattern pattern = Pattern.compile(regex);   
  65.         Matcher matcher = pattern.matcher(str);   
  66.         while (matcher.find()) {   
  67.             //注意要下面的goup()函數(shù)中可以含有數(shù)字,表示查找得到正則表達(dá)式中的goup匹配串.   
  68.             ans.add(matcher.group());   
  69.             System.out.println("找到匹配的字符串 \"" + matcher.group()   
  70.                     + "\" 開(kāi)始于 " + matcher.start()   
  71.                     + " 結(jié)束于 " + matcher.end() + ".");   
  72.         }   
  73.         return ans;   
  74.     }  

 下面是java正則表達(dá)式經(jīng)常使用的一些方法和說(shuō)明:

Java代碼 復(fù)制代碼
  1. 1)使用matches方法快速建設(shè)是否表示給定的輸入字符串:Pattern.matches("\\d","1")返回true  
  2. 2)split(string)使用方法:Pattern.compile(":").split("one:two:three:four:five");  返回:解析出“one two three four five”單詞   
  3. 再比如使用數(shù)字作為一個(gè)分割字符串的方法:(注意下面的\\d不是正則表達(dá)式,而是前面加了一個(gè)轉(zhuǎn)義符號(hào)\)   
  4. Pattern.compile("\\d").split("one9two4three7four1five");也返回相同的結(jié)果。。   
  5. 3)在String類(lèi)中有的幾個(gè)與Pattern類(lèi)似的方法:   
  6. public boolean matches(String regex):   
  7. public String[] split(String regex, int limit):   
  8. public String[] split(String regex):   
  9. public String replace(CharSequence target,CharSequence replacement):   
  10. 4) Matcher 類(lèi)中其他一些有用的方法   
  11. 索引方法   
  12.   索引方法(index methods)提供了一些正好在輸入字符串中發(fā)現(xiàn)匹配的索引值:   
  13.   public int start():返回之前匹配的開(kāi)始索引。   
  14.   public int start(int group):返回之前匹配操作中通過(guò)給定組所捕獲序列的開(kāi)始索引。   
  15.   public int end(): 返回最后匹配字符后的偏移量。   
  16.   public int end(int group): 返回之前匹配操作中通過(guò)給定組所捕獲序列的最后字符之后的偏移量。    
  17. 研究方法   
  18.   研究方法(study methods)回顧輸入的字符串,并且返回一個(gè)用于指示是否找到模式的布爾值。   
  19.   public boolean lookingAt(): 嘗試從區(qū)域開(kāi)頭處開(kāi)始,輸入序列與該模式匹配。   
  20.   public boolean find(): 嘗試地尋找輸入序列中,匹配模式的下一個(gè)子序列。   
  21.   public boolean find(int start): 重置匹配器,然后從指定的索引處開(kāi)始,嘗試地尋找輸入序列中,匹配模式的下一個(gè)子序列。   
  22.   public boolean matches(): 嘗試將整個(gè)區(qū)域與模式進(jìn)行匹配    
  23. 替換方法   
  24.   替換方法(replacement methods)用于在輸入的字符串中替換文本有用處的方法。   
  25.   public Matcher appendReplacement(StringBuffer sb, String replacement):實(shí)現(xiàn)非結(jié)尾處的增加和替換操作。   
  26.   public StringBuffer appendTail(StringBuffer sb):實(shí)現(xiàn)結(jié)尾處的增加和替換操作。   
  27.   public String replaceAll(String replacement):使用給定的替換字符串來(lái)替換輸入序列中匹配模式的每一個(gè)子序列。   
  28.   public String replaceFirst(String replacement):使用給定的替換字符串來(lái)替換輸入序列中匹配模式的第一個(gè)子序列。   
  29.   public static String quoteReplacement(String s):返回指定字符串的字面值來(lái)替換字符串。這個(gè)方法會(huì)生成一個(gè)字符串,用作 Matcher 的 appendReplacement 方法中的字面值替換 s。所產(chǎn)生的字符串將與作為字面值序列的 s 中的字符序列匹配。斜線(\)和美元符號(hào)($)將不再有特殊意義了。   

   正則表達(dá)式基礎(chǔ):

字符類(lèi)
[abc]   a, b 或 c(簡(jiǎn)單類(lèi))
[^abc]         除 a, b 或 c 之外的任意字符(取反)
[a-zA-Z]           a 到 z,或 A 到 Z,包括(范圍)
[a-d[m-p]]              a 到 d,或 m 到 p---等價(jià)于[a-dm-p](并集) (特別注意這里的并集的方式啊,很特別?。。?br>[a-z&&[def]]               d,e 或 f(交集)
[a-z&&[^bc]]              除 b 和 c 之外的 a 到 z 字符等價(jià)于[ad-z](差集)
[a-z&&[^m-p]]                     a 到 z,并且不包括 m 到 p等價(jià)于[a-lq-z](差集)

 

預(yù)定義字符類(lèi)
.         任何字符(匹配或者不匹配行結(jié)束符)
\d         數(shù)字字符:[0-9]
\t        tab鍵
\D         非數(shù)字字符:[^0-9]
\s         空白字符:[\t\n\x0B\f\r]
\S         非空白字符:[^\s]
\w         單詞字符:[a-zA-Z_0-9]
\W         非單詞字符:[^\w]

 

邊界匹配器
^         行首
$         行尾
\b         單詞邊界
\B         非單詞邊界
\A         輸入的開(kāi)頭
\G         上一個(gè)匹配的結(jié)尾
\Z         輸入的結(jié)尾,僅用于最后的結(jié)束符(如果有的話)
\z         輸入的結(jié)尾

 2.使用jxl進(jìn)行exlce的基本操作

下面基礎(chǔ)代碼來(lái)自于網(wǎng)絡(luò):

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

 3.下面含有幾個(gè)十分有用針對(duì)excel操作的的工具方法:

 

Java代碼 復(fù)制代碼
  1. import java.io.File;   
  2. import java.util.ArrayList;   
  3. import java.util.HashMap;   
  4. import java.util.List;   
  5. import java.util.Map;   
  6. import java.util.regex.Matcher;   
  7. import java.util.regex.Pattern;   
  8.   
  9. import jxl.Cell;   
  10. import jxl.CellView;   
  11. import jxl.Sheet;   
  12. import jxl.SheetSettings;   
  13. import jxl.Workbook;   
  14. import jxl.format.Alignment;   
  15. import jxl.write.Label;   
  16. import jxl.write.WritableFont;   
  17. import jxl.write.WritableSheet;   
  18. import jxl.write.WritableWorkbook;   
  19.   
  20. /**  
  21.  * jxl操作excel的工具類(lèi).  
  22.  *  
  23.  */  
  24. public class JxlTool {   
  25.     public static int count = 1;   
  26.     //存儲(chǔ)帶有級(jí)別信息的內(nèi)容到位置的映射關(guān)系.   
  27.     private static Map levelToLocation = new HashMap();   
  28.        
  29.     public static void readExcel(String fileName) {   
  30.         Workbook wb = null;   
  31.         try {   
  32.             wb = Workbook.getWorkbook(new File(fileName));   
  33.             Sheet[] sheets = wb.getSheets();   
  34.             for(int i=0;i<sheets.length;i++){   
  35.                 Sheet ii = sheets[i];   
  36.                 System.out.println("第"+i+"個(gè)sheet的名字是"+ii.getName());   
  37.             }   
  38.         } catch (Exception e) {   
  39.             System.out.println("出現(xiàn)異常" + e);   
  40.             e.printStackTrace();   
  41.         } finally {   
  42.             wb.close();   
  43.         }   
  44.     }   
  45.        
  46.     private static String allChar = "abcdefghijklmnopqrstuvwxyz";   
  47.     /**  
  48.      * 從字符中得到列數(shù).例如K-->10,A-->0,AA-->27  
  49.      * @return  
  50.      */  
  51.     public static int getNumFromExcelStr(String code)   
  52.     {   
  53.         int result = 0;   
  54.         code = code.toLowerCase();   
  55.         if(code.length()>1){   
  56.             char[] c = code.toCharArray();   
  57.             int len = c.length;   
  58.             for(int i=0;i<len;i++){   
  59.                 result+=allChar.indexOf(c[i])+1;   
  60.                 if(i<len-1){   
  61.                     result+=26;   
  62.                 }   
  63.             }   
  64.             result-=1;   
  65.         }   
  66.         else  
  67.             return allChar.indexOf(code);   
  68.         return result;   
  69.     }   
  70.        
  71.     /**  
  72.      * 根據(jù)行號(hào)和列號(hào)得到所在的單元格.例如(3,4)-->"E4"  
  73.      * @param vNum 縱坐標(biāo)  
  74.      * @param hNum 橫坐標(biāo)  
  75.      * @return  
  76.      */  
  77.     public static String getCellInfo(int hNum,int vNum){   
  78.         char[] cs = allChar.toCharArray();   
  79.         String hStr = "";   
  80.         if(vNum>25){   
  81.             hStr = String.valueOf(cs[vNum/26-1])+String.valueOf(cs[vNum%26-1]);   
  82.         }else{   
  83.             hStr = String.valueOf(cs[vNum]);   
  84.         }   
  85.         return (hStr+Integer.toString((hNum+1))).toUpperCase();   
  86.     }   
  87.   
  88.     /**  
  89.      * 得到一個(gè)字符串里面的字符.A12-->A  
  90.      * @param oldStr  
  91.      * @return  
  92.      */  
  93.     public static String getCodeFromStr(String oldStr){   
  94.         return oldStr.replaceAll("\\d""");   
  95.     }   
  96.        
  97.     /**  
  98.      * 得到一個(gè)字符串里面的字符.A12-->12  
  99.      * @param oldStr  
  100.      * @return  
  101.      */  
  102.     public static int getNumFromStr(String oldStr){   
  103.         return Integer.parseInt(oldStr.replaceAll("[a-zA-Z]"""))-1;   
  104.     }   
  105.        
  106.     /**  
  107.      * 讀取指定excel中的指定sheet的某一塊的數(shù)據(jù)....用于模板里面讀取單元格.  
  108.      * @param fileName  
  109.      * @param sheetIndex  
  110.      * @param startRow  
  111.      * @param endRow  
  112.      * @param startColumn  
  113.      * @param endColumn  
  114.      */  
  115.     public static List readExcel(String fileName, int sheetIndex, int startRow,   
  116.             int endRow, int startColumn, int endColumn) {   
  117.         Workbook wb = null;   
  118.         List allData = new ArrayList();   
  119.         Cell cell = null;   
  120.         try {   
  121.             wb = Workbook.getWorkbook(new File(fileName));   
  122.             Sheet sheet = wb.getSheet(sheetIndex);   
  123.             int rowCount = sheet.getRows();   
  124.             int columnCount = sheet.getColumns();   
  125.             for (int r = startRow; r < rowCount && r <= endRow; r++) {// 行   
  126.                 for (int c = startColumn; c < columnCount && c <= endColumn; c++) {// 列   
  127.                     cell = sheet.getCell(c, r);   
  128.                     // System.out.println(cell.getContents());   
  129.                     allData.add(cell.getContents());   
  130.                 }   
  131.             }   
  132.         } catch (Exception e) {   
  133.             System.out.println("出現(xiàn)異常" + e);   
  134.             e.printStackTrace();   
  135.         } finally {   
  136.             wb.close();   
  137.         }   
  138.         return allData;   
  139.     }   
  140.        
  141.     /**  
  142.      * 讀取指定excel中的指定sheet的某一塊的數(shù)據(jù)....用于模板里面讀取單元格.  
  143.      * @param fileName  
  144.      * @param sheetIndex  
  145.      * @param startCell  
  146.      * @param endCell  
  147.      * @return  
  148.      */  
  149.     public static List readExcel(String fileName, int sheetIndex,String startCell, String endCell) {   
  150.         int startRow = getNumFromStr(startCell);   
  151.         int endRow = getNumFromStr(endCell);   
  152.         int startColumn=getNumFromExcelStr(getCodeFromStr(startCell));   
  153.         int endColumn = getNumFromExcelStr(getCodeFromStr(endCell));   
  154.         return readExcel(fileName, sheetIndex, startRow, endRow, startColumn,   
  155.                 endColumn);   
  156.     }   
  157.            
  158.     /**  
  159.      * 設(shè)置excel中的sheet頁(yè)全部隱藏  
  160.      * @param fileName  
  161.      */  
  162.     public static void setAllHiddenSheet(String fileName) {   
  163.         Workbook wb = null;   
  164.         try {   
  165.             wb = Workbook.getWorkbook(new File(fileName));   
  166.             // 打開(kāi)一個(gè)文件副本,并指定數(shù)據(jù)寫(xiě)回原文件.   
  167.             WritableWorkbook book = Workbook.createWorkbook(new File(fileName),   
  168.                     wb);   
  169.             Sheet[] sheets = book.getSheets();   
  170.             for(int i=3;i<sheets.length;i++){   
  171.                 Sheet ii = sheets[i];   
  172.                 ii.getSettings().setHidden(true);   
  173.             }   
  174.             book.write();   
  175.             book.close();   
  176.         } catch (Exception e) {   
  177.             System.out.println("出現(xiàn)異常" + e);   
  178.             e.printStackTrace();   
  179.         } finally {   
  180.             wb.close();   
  181.             System.out.print(111);   
  182.         }   
  183.     }    
  184.     /**  
  185.      * 添加一個(gè)新的sheet到指定excel文件  
  186.      * @param fileName  
  187.      * @param sheetName sheet的name  
  188.      */  
  189.     public static void addNewSheet(String fileName,String sheetName) {   
  190.         Workbook wb = null;   
  191.         try {   
  192.             wb = Workbook.getWorkbook(new File(fileName));   
  193.             // 打開(kāi)一個(gè)文件副本,并指定數(shù)據(jù)寫(xiě)回原文件.   
  194.             WritableWorkbook book = Workbook.createWorkbook(new File(fileName),   
  195.                     wb);   
  196.             // 創(chuàng)建一個(gè)新的sheet到第2頁(yè)的位置              
  197.             String[] sheetNames = wb.getSheetNames();   
  198.             for(int i=0;i<sheetNames.length;i++){   
  199.                 if(sheetNames[i].equals(sheetName)){   
  200.                     System.out.println("已經(jīng)存在了,不用添加了." );   
  201.                     return ;   
  202.                 }   
  203.             }   
  204.             WritableSheet sheet = book.createSheet(sheetName, 1);   
  205.             sheet.addCell(new Label(00"新加的測(cè)試數(shù)據(jù)"));   
  206.             book.write();   
  207.             book.close();   
  208.         } catch (Exception e) {   
  209.             System.out.println("出現(xiàn)異常" + e);   
  210.             e.printStackTrace();   
  211.         } finally {   
  212.             wb.close();   
  213.         }   
  214.     }    
  215. }  

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類(lèi)似文章 更多