Utils

IO:

/**
 * 读取二进制文件并且写入数组里
 * @param filePath 文件全路径
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static byte[] getBytes4File(String filePath) throws IOException {

    InputStream in = null;
    BufferedInputStream buffer = null;
    DataInputStream dataIn = null;
    ByteArrayOutputStream bos = null;
    DataOutputStream dos = null;
    byte[] bArray = null;
    try {
        in = new FileInputStream(filePath);
        buffer = new BufferedInputStream(in);
        dataIn = new DataInputStream(buffer);
        bos = new ByteArrayOutputStream();
        dos = new DataOutputStream(bos);
        byte[] buf = new byte[1024];
        while (true) {
            int len = dataIn.read(buf);
            if (len < 0)
                break;
            dos.write(buf, 0, len);
        }
        bArray = bos.toByteArray();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;

    } finally {

        if (in != null)
            in.close();
        if (dataIn != null)
            dataIn.close();
        if (buffer != null)
            buffer.close();
        if (bos != null)
            bos.close();
        if (dos != null)
            dos.close();
    }

    return bArray;
}

/**
 * 根据全路径获取文件名
 * @param path 文件全路径
 * @return 文件名
 */
public static String getFileNameByPath(String path){
    if (StringUtils.isEmpty(path)){
        return null;
    }
    String[] arr = StringUtils.split(path,'\\');
    return arr[arr.length - 1];
}

/**
 * 获取文件长度
 * @param file 文件
 */
public static Long getFileSize(File file) {
    if (file.exists() && file.isFile()) {
        return file.length();
    }
    return null;
}

EXCEL 2007

package com.zw.nph.core.utils.ExcelUtils;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import com.zw.common.util.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by DELL on 2017/12/6.
 */
public class Excel2007Reader extends DefaultHandler {
    //共享字符串表
    private SharedStringsTable sst;
    //上一次的内容
    private String lastContents;
    private boolean nextIsString;

    private int sheetIndex = -1;
    private ArrayList rowlist = new ArrayList();
    //当前行
    private int curRow = 0;
    //当前列
    private int curCol = 0;
    //日期标志
    private boolean dateFlag;
    //数字标志
    private boolean numberFlag;

    private boolean isTElement;

    private IRowReader rowReader;

    public void setRowReader(IRowReader rowReader){
        this.rowReader = rowReader;
    }

    private boolean hasValue = false;


    /**只遍历一个电子表格,其中sheetId为要遍历的sheet索引,从1开始,1-3
     * @param filename
     * @param sheetId
     * @throws Exception
     */
    public void processOneSheet(String filename,int sheetId) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);

        // 根据 rId# 或 rSheet# 查找sheet
        InputStream sheet2 = r.getSheet("rId"+sheetId);
        sheetIndex++;
        InputSource sheetSource = new InputSource(sheet2);
        parser.parse(sheetSource);
        sheet2.close();
    }

    /**
     * 遍历工作簿中所有的电子表格
     * @param filename
     * @throws Exception
     */
    public void process(String filename) throws Exception {
        OPCPackage pkg = OPCPackage.open(filename);
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();
        XMLReader parser = fetchSheetParser(sst);
        Iterator sheets = r.getSheetsData();
        while (sheets.hasNext()) {
            curRow = 0;
            sheetIndex++;
            InputStream sheet = sheets.next();
            InputSource sheetSource = new InputSource(sheet);
            parser.parse(sheetSource);
            sheet.close();
        }
    }

    public XMLReader fetchSheetParser(SharedStringsTable sst)
            throws SAXException {
        XMLReader parser = XMLReaderFactory
                .createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
        this.sst = sst;
        parser.setContentHandler(this);
        return parser;
    }

    public void startElement(String uri, String localName, String name,
                             Attributes attributes) throws SAXException {

        // c => 单元格
        if ("c".equals(name)) {
            // 如果下一个元素是 SST 的索引,则将nextIsString标记为true
            String cellType = attributes.getValue("t");
            if ("s".equals(cellType)) {
                nextIsString = true;
            } else {
                nextIsString = false;
            }
            //日期格式
//            String cellDateType = attributes.getValue("s");
//            if ("1".equals(cellDateType)){
//                dateFlag = true;
//            } else {
//                dateFlag = false;
//            }
//            String cellNumberType = attributes.getValue("s");
//            if("2".equals(cellNumberType)){
//                numberFlag = true;
//            } else {
//                numberFlag = false;
//            }

        }
        //当元素为t时
        if("t".equals(name)){
            isTElement = true;
        } else {
            isTElement = false;
        }

        // 置空
        lastContents = "";
    }

    public void endElement(String uri, String localName, String name)
            throws SAXException {

        // 根据SST的索引值的到单元格的真正要存储的字符串
        // 这时characters()方法可能会被调用多次
        if (nextIsString) {
            try {
                //防止读取c结尾时 转换出错
                if ("v".equals(name)){
                    int idx = Integer.parseInt(lastContents);
                    lastContents = new XSSFRichTextString(sst.getEntryAt(idx))
                            .toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //t元素也包含字符串
        if(isTElement){
            String value = lastContents.trim();
            rowlist.add(curCol, value);
            curCol++;
            isTElement = false;
            // v => 单元格的值,如果单元格是字符串则v标签的值为该字符串在SST中的索引
            // 将单元格内容加入rowlist中,在这之前先去掉字符串前后的空白符
        } else if ("v".equals(name)) {
            hasValue = true;
            String value = lastContents.trim();
            value = value.equals("")?" ":value;
            //日期格式处理
            //if(dateFlag){
            //    Date date = HSSFDateUtil.getJavaDate(Double.valueOf(value));
            //    SimpleDateFormat dateFormat = new SimpleDateFormat(
            //            "yyyy/MM/dd");
            //    value = dateFormat.format(date);
            //}
            //数字类型处理
            if(numberFlag){
                BigDecimal bd = new BigDecimal(value);
                value = bd.setScale(3,BigDecimal.ROUND_UP).toString();
            }
            rowlist.add(curCol, value);
            curCol++;
        }else if("c".equals(name)){
            if (!hasValue){
                rowlist.add(curCol, "");
                curCol++;
            }else {
                hasValue = false;
            }
        }
        else {
            //如果标签名称为 row ,这说明已到行尾,调用 optRows() 方法
            if (name.equals("row")) {
                rowReader.getRows(sheetIndex,curRow,rowlist);
                rowlist.clear();
                curRow++;
                curCol = 0;
            }
        }

    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        //得到单元格内容的值
        lastContents += new String(ch, start, length);
    }

}
package com.zw.nph.core.utils.ExcelUtils;

/**
 * Created by DELL on 2017/12/11.
 */
public class ExcelReaderUtil {
    //excel2003扩展名
    public static final String EXCEL03_EXTENSION = ".xls";
    //excel2007扩展名
    public static final String EXCEL07_EXTENSION = ".xlsx";

    /**
     * 读取Excel文件,可能是03也可能是07版本
     * @param fileName
     * @throws Exception
     */
    public static void readExcel(IRowReader reader,String fileName) throws Exception{
        // 处理excel2003文件
        if (fileName.endsWith(EXCEL03_EXTENSION)){
            Excel2003Reader excel03 = new Excel2003Reader();
            excel03.setRowReader(reader);
            excel03.process(fileName);
            // 处理excel2007文件
        } else if (fileName.endsWith(EXCEL07_EXTENSION)){
            Excel2007Reader excel07 = new Excel2007Reader();
            excel07.setRowReader(reader);
            excel07.process(fileName);
        } else {
            throw new  Exception("文件格式错误,fileName的扩展名只能是xls或xlsx。");
        }
    }

}

精确小数2位

// 设置精确到小数点后2位     
public static String getPercent(Integer x,Integer total){
   String result = "0.00";
   if(x == null || total == null || total==0||x==0){
      return result;
   }
   return getPercent(x, total.doubleValue());
}


public static String getPercent(Integer x,Double total){
   String result = "0.00";
    if(x == null || total == null || total==0||x==0){
       return result;
    }
    NumberFormat numberFormat = NumberFormat.getInstance();     
    // 设置精确到小数点后2位     
    numberFormat.setMaximumFractionDigits(2);     
    result = numberFormat.format((double)x/(double)total*100);
    String[] strList = result.split("\\.");
    //如果结果大于100,返回100.00
    if (strList[0].length()>=3){
      return "100";
    }
    //保留两位小数
    if (strList.length==2 && strList[1].length()==1){
       result = result+"0";
    }
   if (strList.length==1){
      result = result+".00";
   }
   return result;
}


你可能感兴趣的:(Utils)