package com.example.controller;
import com.alibaba.excel.EasyExcel;
import com.example.entity.ExcelModel;
import com.example.listen.ExcelListenerMore;
import com.example.listen.ExcelListenerOnly;
import com.example.utils.FtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.;
/**
-
测试阿里巴巴上传excle解析
*/
@RestController
@RequestMapping(“/banner”)
public class TestController {@Autowired
private FtpUtil ftpUtil;@PostMapping(“/upload”)
@ResponseBody
public Map<String, String> uploadImg(@RequestParam(“file”) MultipartFile[] file, HttpServletRequest request) throws IOException {
Map<String, String> map = new HashMap<>();
for (MultipartFile multipartFile : file) {
map.put(“code”, “0”);
map.put(“msg”, “上传文件失败”);
String fileName = multipartFile.getOriginalFilename();//获取文件名
String suffixName = fileName.substring(fileName.lastIndexOf(“.”));//获取文件的后缀名
//这里有一个比较重要的信息。因为文件上传如果就是以他的中文名字的话下载下来是为空的就是文件里什么都没有。
//所以在文件上传的时候我先保存了文件信息,然后通过得到文件名去查找这个文件的Id,以他的Id加上后缀作为新的文件名存到ftp服务器中
//上面这个方法就是springdatajpa,不熟悉的同学可以去看博主上一篇文章,或者用你自己的方法取得文件id
fileName = “1”+suffixName;
//上传的文件名也需要加上后缀,不然虚拟机不知道文件格式
InputStream inputStream = multipartFile.getInputStream();
String filePath = null;
//关于ftp处理文件上传下载这里单独写了一个工具类ftpUtil,下面会写这个类
//@Autowired private FtpUtil ftpUtil;service层上面引入了这个方法。
Boolean flag = ftpUtil.uploadFile(fileName, inputStream);//主要就是这里实现了ftp的文件上传
if (flag == true) {
//log.info(“上传文件成功!”);
filePath = ftpUtil.FTP_BASEPATH + fileName;
map.put(“code”, “1”);
map.put(“msg”, “上传文件成功”);
}
map.put(“path”, filePath);
}
System.out.println(map);
return map;
}@PostMapping(“/file”)
public boolean downfile(String path, String id){
//通过文件的id去得到这个文件的所有信息
String type = “pdf”;//取出要下载的这个文件类型
//因为之前存的时候就是用id加后缀存在服务器中的,所以现在也要用同样的名字去查找
id = id+type;//然后用ip加类型作为文件名去下载文件
boolean flag = false;
System.out.println(“文件名:”+id);//这里可以输出一下有没有错
//这里我要得到文件的id和type作为filename去下载,下载是通过filename去对应的目录查找文件名相同的文件下载下来,后台将文件名转换中文文件名。
flag = ftpUtil.downloadFile( “\huanglong” , id,path);//下载调用service层的方法
System.out.println(flag);
return flag;
}@PostMapping(“uploadExcelOnly”)
public void uploadExcelOnly(MultipartFile excelFile) throws IOException {
ExcelListenerOnly listener = new ExcelListenerOnly(); //ExcelListener 上面创建的那个类
EasyExcel.read(excelFile.getInputStream(), ExcelModel.class,listener).sheet(0).doReadSync(); //ExcelModel 上面创建的实体类
System.out.println(“解析完之后的数据:—”+listener.getDatas());
List datas = listener.getDatas(); //把拿到的数据处理到集合里去(根据所需自行修改)
//baseService.insertExcelService(datas);//入库
datas.clear();//结束后销毁不用的资源
System.out.println(datas); //查看销毁后的结果
}@PostMapping(“uploadExcelMore”)
public int getExcelDataMore(MultipartFile excelFile, String type) throws IOException {
ExcelListenerMore listener = new ExcelListenerMore();
int i =0;
if (“agricul”.equals(type)){ //根据传过来的type来判断用哪个模板(实体类)
List objects = EasyExcel.read(excelFile.getInputStream(), ExcelModel.class, listener).sheet(0).doReadSync();
for (Object ii:objects) {
ExcelModel mod= (ExcelModel) ii; //把拿过来的Object转换成具体实体类
if(mod.getCityid()==null || mod.getCounttotal()==null || mod.getNtptwoid()==null ||mod.getCityid()==0){ //做一些简单的判断
continue;
}
//i = mpntpMapper.insert(mod); //入库
}
}
return i;
}@PostMapping(“/downloadExcel”)
public void downloadExcel(HttpServletResponse response) throws Exception {
response.setContentType(“application/vnd.ms-excel”);
response.setCharacterEncoding(“utf-8”);
//List list = baseService.selectExcelService(); //数据库中获取的数据
List list = new ArrayList<>(); //数据库中获取的数据
String fileName = URLEncoder.encode(UUID.randomUUID().toString().replaceAll(“-”,“”), “UTF-8”);
response.setHeader(“Content-disposition”, “attachment;filename=”+fileName+“.xlsx”);
EasyExcel.write(response.getOutputStream(),ExcelModel.class).sheet(“sheet1”).doWrite(list);
}
}
package com.example.utils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;
import java.io.*;
@Component//这就是我们刚才加入的依赖
public class FtpUtil {
//ftp服务器ip地址
private static final String FTP_ADDRESS = "19.32";
//端口号
private static final int FTP_PORT = 21;
//用户名
private static final String FTP_USERNAME = "huang";
//密码
private static final String FTP_PASSWORD = "126";
//路径都是/home/加上用户名
public final String FTP_BASEPATH = "/home/huanng";
//参数传过来了文件和文件的输入流
public boolean uploadFile(String originFileName, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();//这是最开始引入的依赖里的方法
ftp.setControlEncoding("utf-8");
try {
int reply;
ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
reply = ftp.getReplyCode();//连接成功会的到一个返回状态码
System.out.println(reply);//可以输出看一下是否连接成功
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件类型
ftp.changeWorkingDirectory(FTP_BASEPATH);//修改操作空间
//对了这里说明一下你所操作的文件夹必须要有可读权限,chomd 777 文件夹名//这里我就是用的我的home文件夹
ftp.storeFile(originFileName, input);//这里开始上传文件
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("连接失败");
return success;
}
System.out.println("连接成功!");
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
public boolean downloadFile(String pathname, String filename, String localpath) {
boolean flag = false;
FTPClient ftp = new FTPClient();
OutputStream os = null;
try {
System.out.println("开始下载文件");
ftp.connect(FTP_ADDRESS, FTP_PORT);// 连接FTP服务器
ftp.login(FTP_USERNAME, FTP_PASSWORD);// 登录
int reply = ftp.getReplyCode();//得到连接成功的返回状态码
System.out.println(reply);
ftp.enterLocalActiveMode();//主动,一定要加上这几句设置为主动
//下面是将这个文件夹的所有文件都取出来放在ftpFiles这个文件数组里面
FTPFile[] ftpFiles = ftp.listFiles();
//然后便利这个数组找出和我们要下载的文件的文件名一样的文件
for (FTPFile file : ftpFiles) {
byte[] bytes = file.getName().getBytes("ISO-8859-1");
file.setName(new String(bytes, "utf-8"));
System.out.println("name: " + file.getName());//
if (filename.equalsIgnoreCase(file.getName())) {//判断找到所下载的文件,file.getName就是服务器上对应的文件
//下面就是通过文件id再去数据库查找文件的中文名,将这个作为文件名下载到本地目录
String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
System.out.println("该文件的id:"+fileName);
fileName = "tew.pdf";
File localFile = new File(localpath + "/" + fileName);
os = new FileOutputStream(localFile);//得到文件的输出流
ftp.retrieveFile(file.getName(), os);//开始下载文件
os.close();
}
}
ftp.logout();
flag = true;
System.out.println("下载文件成功");
} catch (Exception e) {
System.out.println("下载文件失败");
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
}
package com.example.listen;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.entity.ExcelModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
-
单个模板的操作
*/
public class ExcelListenerOnly extends AnalysisEventListener {// ExcelModel :实体类
//自定义用于暂时存储data。
//可以通过实例获取该值
private List datas = new ArrayList<>();
//private List<Map<String,Object>> datas = new ArrayList<>(); //根据需求也可选择用map来接收
// @Override
// public void invoke(Map<String,Object> map, AnalysisContext analysisContext) {
// datas.add(map);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
// }
@Override
public void invoke(ExcelModel excelModel, AnalysisContext analysisContext) {//此方法一行一行的读取Excel内容
if (excelModel.getUsername() != null) { //做一个简单的判断,可根据自己的业务逻辑更改
datas.add(excelModel);//数据存储到list,供批量处理,或后续自己业务逻辑处理。
}
}
public void doAfterAllAnalysed(AnalysisContext context) {
// datas.clear();//解析结束销毁不用的资源,也可待数据入库后在进行销毁,根据具体业务需求自行更改
}
public List<ExcelModel> getDatas() { //把存储的数据通过此方法暴露出去
return datas;
}
}
package com.example.listen;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
/**
-
多个模板的操作
*/
public class ExcelListenerMore extends AnalysisEventListener { //在这里不给它指定具体模板(实体类)@Override
public void invoke(Object obj, AnalysisContext analysisContext) {
System.out.println(“读取的很一行的数据:—”+obj);
}public void doAfterAllAnalysed(AnalysisContext context) {
// datas.clear();//解析结束销毁不用的资源
}
}
package com.example.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;
import org.springframework.context.annotation.Scope;
@Scope(“prototype”)
@Data //此注释需要导入lombok
@ContentRowHeight(25) //数据表格列高
@HeadRowHeight(20) //标题表格列高
@ColumnWidth(25) //标题表格列宽
public class ExcelModel {
@ExcelProperty(value = "姓名",index = 0) //index表示读取的数据在第几列,根据业务需求自行对应
private String username;
@ExcelProperty(value = "年龄",index = 1)
private String userage;
@ExcelProperty(value = "邮箱",index = 2)
private String useremail;
@ExcelProperty(value = "城市",index = 3)
private Long cityid;
@ExcelProperty(value = "城市人口",index = 4)
private Long counttotal;
@ExcelProperty(value = "邮箱",index = 5)
private String ntptwoid;
}
package com.example.utils;
import com.alibaba.excel.EasyExcel;
import com.example.entity.ExcelModel;
import com.example.listen.ExcelListenerOnly;
import java.util.ArrayList;
import java.util.List;
/**
-
测试阿里巴巴easyexcel上传excel
*/
public class TestEasyExcel {public static void main(String[] args) {
//实现excel写的操作
//1 设置写入文件夹地址和excel文件名称
String filenamew = “F:\data\test.xlsx”;
//2 调用easyexcel里面的方法实现写操作
//write方法两个参数:第一个参数文件路径名称,第二个参数实体类class
EasyExcel.write(filenamew,ExcelModel.class).sheet(“学生列表”).doWrite(getData());
//实现excel读的操作
String filenamer = “F:\data\test.xlsx”;
ExcelListenerOnly excelListenerOnly = new ExcelListenerOnly();
EasyExcel.read(filenamer, ExcelModel.class,excelListenerOnly).sheet().doRead();
List datas = excelListenerOnly.getDatas();
System.out.println(datas);
datas.clear();
}private static List getData() {
List list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ExcelModel data = new ExcelModel();
data.setUsername(“张三”);
data.setUserage(“lucy”);
data.setUseremail(“212”);
list.add(data);
}
return list;
}
}