Excel 파일 (xls / xlsx) 에서 자바 빈 도구 로 전환 하 는 실현

10446 단어
요약 Excel 파일 을 javabean 으로 변환 하려 면 보통 Apache POI 도 구 를 사용 합 니 다. 이 도 구 는 마이크로소프트 사무 용 소프트웨어 를 전문 적 으로 다 루 는 도구 입 니 다.간단 하지만 시간 이 걸 려 xlstoBean 같은 기 똥 찬 방법 을 제공 하지 않 았 다.이번 에는 꼭 필요 해서 동료 들 의 방법 을 봤 어 요 ~ 오 르 즈 가 무릎 을 꿇 었 어 요.프로그래머 인 이상 인력 으로 문 제 를 해결 하지 말고 알고리즘 으로 해결 하기 때문에 도 구 를 직접 써 서 자신 을 편리 하 게 하고 다른 사람 을 편리 하 게 한다.
동료 들 의 방법 부터 살 펴 보 겠 습 니 다.
public static List getListByExcel(String file) throws BiffException, IOException, MyException{
        List list=new ArrayList();
        Workbook rwb=Workbook.getWorkbook(new File(file));
        Sheet rs=rwb.getSheet("  ");
        if(rs==null) {
            throw new MyException("    ");
        }
        int rows=rs.getRows();
        for (int i = 1; i < rows; i++) {
            if(rs.getCell(0, i).getContents()==null||rs.getCell(0, i).getContents().equals("")) {
                break;
            }
            String name=rs.getCell(1, i).getContents();
            String format=rs.getCell(2, i).getContents();
            String unit=rs.getCell(3, i).getContents();
            String factory=rs.getCell(4, i).getContents();
            String price=rs.getCell(5, i).getContents();
            String conversion=rs.getCell(6, i).getContents();
            String tname=rs.getCell(7, i).getContents();
            String tformat=rs.getCell(8, i).getContents();
            String tunit=rs.getCell(9, i).getContents();
            String tfactory=rs.getCell(10, i).getContents();
            String tprice=rs.getCell(11, i).getContents();
            String tendGoodsId=rs.getCell(12, i).getContents();
            String goodsId=rs.getCell(13, i).getContents();
            String factoryId=(rs.getCell(14, i).getContents()==null||rs.getCell(14, i).getContents().equals(""))?"0":rs.getCell(14, i).getContents();
            GoodsEntity a = new GoodsEntity();
            a.setName(name);
            a.setFormat(format);
            a.setUnit(unit);
            a.setFactory(factory);
            a.setPrice(price);
            a.setTend_goodsId(tendGoodsId);
            a.setGoodsId(goodsId);
            a.setFactoryId(factoryId);
            a.setUuId(UUID.randomUUID().toString());
            a.setTfactory(tfactory);
            a.setTformat(tformat);
            a.setTname(tname);
            a.setTunit(tunit);
            a.setConversion(conversion);
            a.setTprice(tprice);
            list.add(a);
        }
        return list;
    }

이것 은 단지 그 중의 javabean 의 전환 방법 일 뿐이다.해당 클래스 에는 현재 10 개 정도 의 변환 방법 이 있 지만 코드 는 이미 484 줄 이 있다.이 프로젝트 는 이제 막 시작 되 었 는데, 후기 에 이 르 러 서 야 어찌 수천 줄 에 수만 줄 이 필요 하지 않 겠 는가?
먼저 제 생각 을 말씀 드 리 고 위조 코드 를 직접 보 는 것 이 좋 습 니 다.
File file = new File(excel  ); 

WorkBook wb = new Workbook(file); //excel        

Row row = wb.getSheet(0).getRow(  );//  excel    
//     ,        JavaBean

int cols = row.getLastCellNum();//         

Object[] arr = new Object[cols];

//           ,                arr
for(int i = 0 ;i

내 코드 봐, BB 아니 야.
Excel Cell. java 주석
/** 
* @ClassName: ExcelCell 
* @Description:      excel       
* @author albert
*  
*/
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelCell {
    int col();
    Class> Type() default String.class;
}

엑셀 파일
상품 명
단위
규격.
생산 업 체
감기 영 과립
상자.
3 장 / 박스
귀주 백 령
excel 파일 은 모두 4 열 이 있 습 니 다. 그러면 번호 0 - 3;
Goods. java 실체 클래스
Excel 열 번호 와 대응 할 수 있 도록 실체 클래스 속성 에 주 해 를 추가 해 야 합 니 다.
public class Goods{
  @ExcelCell(col=0)
  private String name; //   

  @ExcelCell(col=1)
  private String unit; //  

  @ExcelCell(col=2)
  private String format; //  

  @ExcelCell(col=3)
  private String factory;//    
}

가장 중요 한 도구 클래스: ExcelConvert. java
/**
 * 
 */
package com.sy.utils;

/** 
* @ClassName: ExcelConveter 
* @Description: 
* @author albert
* @date 2017 5 5    1:19:56 
*  
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.sy.exceptions.MyException;

public class ExcelConveter {
    
    public static Workbook readFile(File file) throws MyException {
        try {
            //xls xlsx        ,POI      
            if (file.getName().toLowerCase().endsWith(".xls")) {
                return readFileHSSF(new FileInputStream(file));
            } else {
                return readFileXSSF(new FileInputStream(file));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
    }
    //HSSF*   xls   ,XSSF   xlsx    
    private static Workbook readFileHSSF(InputStream stream) throws MyException, IOException {
        try {
            return new HSSFWorkbook(stream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        } finally {
            stream.close();
        }
    }

    private static Workbook readFileXSSF(InputStream stream) throws MyException, IOException {
        try {
            return new XSSFWorkbook(stream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        } finally {
            stream.close();
        }
    }

    public static Workbook readFile(String path) throws MyException {
        File file = new File(path);
        if (!file.exists())
            throw new MyException("     ");
        if (!file.isFile())
            throw new MyException("       ");
        return readFile(file);
    }

    public static Sheet readSheet(HSSFWorkbook workbook, Integer index) {
        return workbook.getSheetAt(index);
    }

    public static Object[] convertArrayByRow(Row row) {
        int cols = row.getLastCellNum();
        Object[] arr = new Object[cols];
        for (int i = 0; i < cols; i++) {
            Cell cell = row.getCell(i);
            if (cell == null)
                continue;
            if (cell.getCellTypeEnum() == CellType.STRING) {
                arr[i] = cell.getStringCellValue();
            } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
                arr[i] = cell.getNumericCellValue();
            } else {

            }
        }
        return arr;
    }

    public static  T convertBeanFromArray(Object[] arr, Class clazz) throws MyException {
        T entity;
        try {
            entity = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(ExcelCell.class))
                    continue;

                field.setAccessible(true);
                ExcelCell anno = field.getAnnotation(ExcelCell.class);
                Class> cellType = anno.Type();
                Integer col = anno.col();

                if (col >= arr.length)
                    continue;
                if (arr[col] == null)
                    continue;
                if (cellType == null) {
                    field.set(entity, arr[col]);
                } else {
                    field.set(entity, numericByStr(cellType, arr[col]));
                }
            }
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
    }

    public static  Object numericByStr(Class clazz, Object param) {
        if (param == null)
            return null;
        String arg = String.valueOf(param);
        if (clazz.isAssignableFrom(Double.class)) {
            return Double.valueOf(arg);
        } else if (clazz.isAssignableFrom(Long.class)) {
            Double d = Double.valueOf(arg);
            return d.longValue();
        } else if (clazz.isAssignableFrom(Integer.class)) {
            return Integer.valueOf(arg);
        } else {
            return arg;
        }
    }

    public static  List getBean(String path, Class clazz) throws MyException {
        List list = new ArrayList();
        Workbook book = readFile(path);
        for (int i = 1; i <= book.getSheetAt(0).getLastRowNum(); i++) {
            Object[] arr = convertArrayByRow(book.getSheetAt(0).getRow(i));
            T t = convertBeanFromArray(arr, clazz);
            list.add(t);
        }
        return list;
    }

    public static  List getBean(File file, Class clazz) throws MyException {
        List list = new ArrayList();
        Workbook book = readFile(file);
        for (int i = 1; i <= book.getSheetAt(0).getLastRowNum(); i++) {
            Object[] arr = convertArrayByRow(book.getSheetAt(0).getRow(i));
            T t = convertBeanFromArray(arr, clazz);
            list.add(t);
        }
        return list;
    }

    public static  List getBean(InputStream stream, String excelType, Class clazz)
            throws MyException, IOException {
        Workbook book;
        if (excelType.equals("xls")) {
            book = readFileHSSF(stream);
        } else {
            book = readFileXSSF(stream);
        }
        List list = new ArrayList();
        for (int i = 1; i <= book.getSheetAt(0).getLastRowNum(); i++) {
            Object[] arr = convertArrayByRow(book.getSheetAt(0).getRow(i));
            T t = convertBeanFromArray(arr, clazz);
            list.add(t);
        }
        return list;
    }
}


사용법: 이 한 줄, 아주 간단 하지 않 습 니까?
List list = ExcelConveter.getBean('excel    ', Barcode.class);

필요 한 jar 가방 은 apache 홈 페이지 에서 다운로드 할 수 있 습 니 다.http://poi.apache.org/download.html#POI-3.16

좋은 웹페이지 즐겨찾기