项目有个需求导入excel信息,但是有个列存放的图片,比如用户头像,奇奇怪怪的需求,下面告诉大家我是怎么实现的。
excel模版如下
前端Vue,上传代码如下
<!--上传按钮-->
<el-upload class="upload-demo" action='' :show-file-list="false" :before- upload="beforeUpload" :on-success="handleAvatarSuccess" :limit="1">
<el-button size="small" type="primary" class="bt-upload">批量上传</el-button>
</el-upload>
<!-- js方法调用 -->
beforeUpload(file) {
// 1. 创建formData
const formData = new FormData();
formData.append('file', file);
const config = {
'Content-Type': 'multipart/form-data'
};
// const var_this = this;
upLoad(formData, config).then(res => {
if (res.rel) {
this.$notify({
title: '成功',
message: '添加成功',
type: 'success',
duration: 2000
});
this.getList();
} else {
this.$notify({
title: '失败',
message: '添加失败,请确认表格数据是否正确!',
type: 'fail',
duration: 2000
});
}
}).catch(function(error) {
this.$message.error('图片上传失败!' + error);
});
}
handleAvatarSuccess(res) {
this.form.guestImg = res.data
}
// 其中upload方法为封装的axios
// 批量上传
export function upLoad(formData, config) {
return fetch({
url: '/admin/baseMeetingUser/upMeetingUserExcel',
method: 'post',
data: formData,
header: config
});
}
后台java代码如下:
@ApiOperation(value="上传参会用户信息接口", notes="上传Excel接口,上传参会用户信息接口")
@PostMapping(value = "/upMeetingUserExcel")
@ResponseBody
public ObjectRestResponse upMeetingUserExcel(@RequestParam(value = "file",required = true) MultipartFile file) {
try {
Workbook workbook = WorkbookFactory.create(file.getInputStream());
//获取第一个工作表
Sheet sheet = workbook.getSheetAt(0);
Map<String, PictureData> maplist=null;
// 判断用07还是03的方法获取图片
if (SaveImgUnit.getExtensionName(file.getOriginalFilename()).endsWith("xls")) {
maplist = UploadUtils.getPictures1((HSSFSheet) sheet);
} else if(SaveImgUnit.getExtensionName(file.getOriginalFilename()).endsWith("xlsx")){
maplist = UploadUtils.getPictures2((XSSFSheet) sheet);
}
//获取sheet中最后一行行号
int lastRowNum = sheet.getLastRowNum();
for(int i = 1; i<= lastRowNum;i++){
TbMeetingUser user =new TbMeetingUser();
Row row = sheet.getRow(i);
user.setUserName(row.getCell(0).getStringCellValue());
if(row.getCell(1) != null){
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
String phoneNum =row.getCell(1).getStringCellValue();
if(phoneNum.length()!= 11){
return new ObjectRestResponse<>().rel(false);
}else{
Pattern p = Pattern.compile(Constants.IPHONE_REGEX);
Matcher m = p.matcher(phoneNum);
boolean isMatch = m.matches();
if(isMatch){
user.setPhoneNum(row.getCell(1).getStringCellValue());
}else{
return new ObjectRestResponse<>().rel(false);
}
}
}
user.setCompany(row.getCell(2).getStringCellValue());
user.setPosition(row.getCell(3).getStringCellValue());
//0不是嘉宾
int guest = 0;
if(row.getCell(4).getStringCellValue().equals("是")){
guest = 1;
}
user.setGuest(guest);
user.setGuestIntroduce(row.getCell(5).getStringCellValue());
if(null != maplist){
for(Iterator iter =maplist.entrySet().iterator();iter.hasNext();){
Map.Entry element = (Map.Entry)iter.next();
String strKey = element.getKey().toString();
Object strValue = element.getValue();
String[] parts = strKey.split("-");
int row1 = -1;
int col1 = -1;
if(!StringUtils.isEmpty(parts[0])){
row1 = Integer.parseInt(parts[0]);//行号
}
if(!StringUtils.isEmpty(parts[1])){
col1 = Integer.parseInt(parts[1]);//列号
}
if(row1 == i && col1 == 6){
PictureData pd = maplist.get(strKey);
byte[] data = pd.getData();
//上传文件路径
String path = GetServerRealPathUnit.getPath(uploadFolder);
//重新修改文件名防止重名
String filename = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)+ "."+SaveImgUnit.getExtensionName(file.getOriginalFilename());
File filepath = new File(path, filename);
//判断路径是否存在,没有就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
FileOutputStream out = new FileOutputStream(path+filename);
out.write(data);
out.close();
String host="localhost";
try {
if(StringUtils.isEmpty(netIpAddr)){
host=InetAddress.getLocalHost().getHostAddress();
}else{
host = netIpAddr;
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
//fileUrl为图片对外访问路径
String fileUrl = "http://" + host + ":" + serverPort+foundImgPath+filename;
System.out.println("参会用户头像上传地址:"+fileUrl);
user.setGuestImg(fileUrl);
}
}
}
user.setCreateAt(new Date());
meetingUserBiz.insertSelective(user);
}
}catch(Exception e){
return new ObjectRestResponse<>().rel(false);
}
return new ObjectRestResponse<>().rel(true);
}
UploadUtils类,(参考了网上别的大佬写的):
package com.smartt.bylf.security.admin.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
@Component
public class UploadUtils {
static Logger logger = LoggerFactory.getLogger(UploadUtils.class);
/**
* 获取图片和位置 (xls)
* @param sheet
* @return
* @throws IOException
*/
public static Map<String, PictureData> getPictures1 (HSSFSheet sheet) throws IOException {
Map<String, PictureData> map = new HashMap<String, PictureData>();
List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
for (HSSFShape shape : list) {
if (shape instanceof HSSFPicture) {
HSSFPicture picture = (HSSFPicture) shape;
HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
PictureData pdata = picture.getPictureData();
String key = cAnchor.getRow1() + "-" + cAnchor.getCol1(); // 行号-列号
map.put(key, pdata);
}
}
return map;
}
/**
* 获取图片和位置 (xlsx)
* @param sheet
* @return
* @throws IOException
*/
public static Map<String, PictureData> getPictures2 (XSSFSheet sheet) throws IOException {
Map<String, PictureData> map = new HashMap<String, PictureData>();
List<POIXMLDocumentPart> list = sheet.getRelations();
for (POIXMLDocumentPart part : list) {
if (part instanceof XSSFDrawing) {
XSSFDrawing drawing = (XSSFDrawing) part;
List<XSSFShape> shapes = drawing.getShapes();
for (XSSFShape shape : shapes) {
XSSFPicture picture = (XSSFPicture) shape;
XSSFClientAnchor anchor = picture.getPreferredSize();
CTMarker marker = anchor.getFrom();
String key = marker.getRow() + "-" + marker.getCol();
map.put(key, picture.getPictureData());
}
}
}
return map;
}
/**
* 获得excel中所有图片
*
* @param sheet
* @throws IOException
*/
public static void readPictures(HSSFSheet sheet) throws IOException {
try {
List<HSSFShape> list = sheet.getDrawingPatriarch().getChildren();
for (HSSFShape shape : list) {
if (shape instanceof HSSFPicture) {
HSSFPicture picture = (HSSFPicture) shape;
HSSFPictureData pdata = picture.getPictureData();
String extension = pdata.suggestFileExtension();
GenerateImage(byteToBase64String(pdata.getData()), (new Random().nextInt(9000) % (9000 - 1000 + 1) + 1000)+"", extension);
}
}
} catch (Exception e) {
logger.error("e", e);
}
}
/**
* 二进制数据转化为BASE64字符串
*
* @param b
* @return
*/
public static String byteToBase64String(byte[] b) {
return new String(Base64.encodeBase64(b));
}
/**
* 生成图片
*
* @param imgStr
* @param name
* 图片名
* @param extension
* 后缀、扩展名
* @return
*/
public static boolean GenerateImage(String imgStr, String name, String extension) {
try {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
String path = "E://";
String imgFilePath = path + name + "." + extension;// 新生成的图片
logger.info("生成的图片:{}", imgFilePath);
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
} catch (Exception e) {
logger.error("e", e);
}
return false;
}
}
整个功能代码就是这样,有问题的欢迎下方留言