根据上传的excel文件url,进行文件查询

HttpResponse response = HttpUtil.createGet(fileUrl)
.setConnectionTimeout(20000)
.setReadTimeout(120000)
.timeout(3600000)
.execute();
InputStream inputStream = response.bodyStream();
boolean xls = ExcelFileUtil.isXls(inputStream);
boolean xlsx = ExcelFileUtil.isXlsx(inputStream);
if(!xls&&!xlsx){
return R.failed("不是Excel文件!");
}

MultipartFile multipartFile = getMultipartFile(inputStream, "read.xlsx");
try {
InputStream inputStreamOther = multipartFile.getInputStream();
//使用hutool的类,内部其实还是调用WorkbookFactory.create方法,只不过多了个关闭流的操作
Workbook workbook = WorkbookUtil.createBook(inputStreamOther);
Sheet sheet = workbook.getSheetAt(0);
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
Row row = sheet.getRow(firstRowNum);
String s;
for (int i = 0; i < ODPS_CZRKXXSJB_IMPORT.length; i++) {
s = row.getCell(i).getStringCellValue();
if (StrUtil.isBlank(s)) {
return R.failed("警告!模板为空或有误!");
}
if (!ODPS_CZRKXXSJB_IMPORT[i].equals(s)) {
return R.failed("警告!模板为空或有误!第 " + (i + 1) + " 列名错误");
}
}
} catch (IOException e) {
e.printStackTrace();
}




/**
* 获取封装得MultipartFile
*
* @param inputStream inputStream
* @param fileName fileName
* @return MultipartFile
*/
public MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
FileItem fileItem = createFileItem(inputStream, fileName);
//CommonsMultipartFile是feign对multipartFile的封装,但是要FileItem类对象
return new CommonsMultipartFile(fileItem);
}


/**
* FileItem类对象创建
*
* @param inputStream inputStream
* @param fileName fileName
* @return FileItem
*/
public FileItem createFileItem(InputStream inputStream, String fileName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
OutputStream os = null;
//使用输出流输出输入流的字节
try {
os = item.getOutputStream();
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
inputStream.close();
} catch (IOException e) {
log.error("Stream copy exception", e);
throw new IllegalArgumentException("文件上传失败");
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("Stream close exception", e);

}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("Stream close exception", e);
}
}
}

return item;
}
posted @ 2023-06-25 17:02  全琪俊  阅读(56)  评论(0编辑  收藏  举报