Java通过jxl读取Excel

package com.hd.all.test.testjava;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ReadExcelJXL {

    public static void main(String[] args) throws BiffException, IOException {
        //Exception in thread "main" jxl.read.biff.BiffException: Unable to recognize OLE stream
        //1.不能读取2007版本的Excel;2.java生成的也不能读取
        
//        File file = new File("E:/students2017-10-19_10_55_55.xls");
        /**
         * 读Excel内容
         */
        File file = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\1.xls");
        Workbook wb = Workbook.getWorkbook(file);
        Sheet s = wb.getSheet("Sheet1");
        /**
         * 写Excel内容
         */
        WritableWorkbook book = Workbook.createWorkbook(new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\2.xls"));
        WritableSheet sheet = book.createSheet("Sheet1", 0);
        
        String reg = "1[0-9][A-Z]{2,3}[0-9]{5,6}";//匹配15KF111111
        Pattern p = Pattern.compile(reg);
        
        String reg1 = "100[0-9]{5}";//匹配10011111
        Pattern p1 = Pattern.compile(reg1);
        
        String reg2 = "2[0-9]{11}-{0,1}[0-9]{0,1}";//匹配211111111111(-n)-->211111111111-2
        Pattern p2 = Pattern.compile(reg2);
        
        Cell c = null;
        int i = 1;
        while(true){
            c = s.getCell(0,i);//第i行第二列,0是第一列
            Matcher m = p.matcher(c.getContents());//匹配15KF111111
            Matcher m1 = p1.matcher(c.getContents());//匹配10011111
            Matcher m2 = p2.matcher(c.getContents());//匹配211111111111
            try {
                if(m.find()){
                    sheet.addCell(new Label(2,i,m.group(0)));//如果是鼎捷料号输出
                }else{
                    if(m2.find()){
                        sheet.addCell(new Label(2,i,m2.group(0)));
                    }else{
                        if(m1.find()){
                            sheet.addCell(new Label(3,i,m1.group(0)));//如果是10011111格式的输出
                        }
                    }
                }
            } catch (Exception e) {
            }
            
            i++;
            if (i > 753)//Excel的行数减1
                break;
        }
        book.write();
        try {
            book.close();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/suhfj-825/p/9044656.html