前提:需要引入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文件读取工具文章来源:https://www.toymoban.com/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文件上传文章来源地址https://www.toymoban.com/news/detail-528852.html
public R importProduct(MultipartFile file) throws IOException {
List<ProductReq.ProductImportReq> excelVOList = new ExcelAnalysisUtil().readFile(file,ProductReq.ProductImportReq.class,2);
//业务实现
}
到了这里,关于EXCEL上传指定行读取数据 可直接使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!