前提:需要引入easyExcel
EXCEL上傳指定行讀取數據
前置條件
entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static class ProductImportReq{
@ExcelProperty(value = "外部商品編碼",index = 0)
@ApiModelProperty(value="外部產品編碼")
private String externalProductCode;
@ExcelProperty(value = "商品編碼",index = 1)
@ApiModelProperty(value = "商品編碼")
private String productCode;
/**
* 產品名稱
*/
@ExcelProperty(value = "商品名稱",index = 2)
@ApiModelProperty(value = "產品名稱")
private String productName;
@NotNull(message = "是否標品")
@ExcelProperty(value = "是否標品",converter = IntegerConverter.class,index = 3)
@ApiModelProperty(value = "是否標準品0 否 1是")
private Integer isStandard;}
中文數字轉換器
public class IntegerConverter implements Converter<Integer> {
@Override
public Class supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
Integer result=null==cellData.getStringValue()?null:"是".equals(cellData.getStringValue()) ? 1 : 0;
return result;
}
@Override
public WriteCellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new WriteCellData<String>(Objects.equals(value, 1) ? "是" : "否");
}
}
1.繼承AnalysisEventListener
public class DataEasyExcelListener <T> extends AnalysisEventListener { private List<T> list = new ArrayList<>(); @Override public void invoke(Object data, AnalysisContext analysisContext) { list.add((T) data); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } public List<T> getData() { return list; } }
2.EXCEL文件讀取工具文章來源:http://www.zghlxwxcb.cn/news/detail-528852.html
public class ExcelAnalysisUtil<T> {
public List<T> readFile(MultipartFile file,Class head,Integer rowIndex) throws IOException {
DataEasyExcelListener<ProductReq.ProductImportReq> listener = new DataEasyExcelListener<>();
EasyExcel.read(file.getInputStream(), head, listener).sheet(0).headRowNumber(rowIndex).doRead();
return (List<T>) listener.getData();
}
public List<T> readFile(MultipartFile file,Class head) throws IOException {
return readFile(file,head,0);
}
}
3.excel文件上傳文章來源地址http://www.zghlxwxcb.cn/news/detail-528852.html
public R importProduct(MultipartFile file) throws IOException {
List<ProductReq.ProductImportReq> excelVOList = new ExcelAnalysisUtil().readFile(file,ProductReq.ProductImportReq.class,2);
//業(yè)務實現
}
到了這里,關于EXCEL上傳指定行讀取數據 可直接使用的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!