Excel 파일 (xls / xlsx) 에서 자바 빈 도구 로 전환 하 는 실현
동료 들 의 방법 부터 살 펴 보 겠 습 니 다.
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.