当前位置:网站首页>Easyexcel realizes simple uploading and downloading
Easyexcel realizes simple uploading and downloading
2022-06-10 07:42:00 【Catch wind and shadow】
Need to import pom:
<!-- easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
<!-- easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>
controller:
/**
* Derived data
*/
@RequestMapping("/export")
public void export(HttpServletResponse response) throws IOException {
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(" Address .xlsx", "UTF-8"));
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
WriteSheet sheet = EasyExcel.writerSheet(0).head(tAddressCity.class).build();
List<addressDto> list = addressService.filefindAll();
excelWriter.write(list, sheet);
excelWriter.finish();
}
/**
* Download the template
*/
@RequestMapping("/downloadModel")
public void downloadModel(HttpServletResponse response) throws IOException {
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(" Templates .xlsx", "UTF-8"));
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
WriteSheet sheet = EasyExcel.writerSheet(0).head(tAddressCity.class).build();
excelWriter.write(Collections.emptyList(), sheet);
excelWriter.finish();
}
/**
* @param serviceFile excel file
* @return Note that the request parameter is file
* @throws IOException abnormal
*/
@PostMapping(value = "/upload")
@ResponseBody
public String uploadEasyExcel(@RequestParam(value = "file") MultipartFile serviceFile) throws IOException {
ExcelReader excelReader = null;
@Cleanup InputStream in = null;
try {
in = serviceFile.getInputStream();
// Note the data to be parsed here User3.class
excelReader = EasyExcel.read(in, tAddressCity.class, new ExcelListener()).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
} catch (IOException ex) {
log.error("import excel to db fail", ex);
}
finally {
in.close();
// Don't forget to close here , Temporary files will be created when reading , The disk will crash @Cleanup Notes are more concise
if (excelReader != null) {
excelReader.finish();
}
}
return " Parsing succeeded , And put it into storage ";
}
Monitor :
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.yjxxt.crm.bean.tAddressCity;
import com.yjxxt.crm.dao.AddressDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
/**
* ExcelListener:Excel Monitor
* @author liuyang
*/
@Slf4j
public class ExcelListener extends AnalysisEventListener {
@Autowired
AddressDao addressDao;
private static final int BATCH_COUNT = 1000;
private List<Object> objectList = new ArrayList(10);
@Override
public void invoke(Object o, AnalysisContext analysisContext) {
log.info(" Parse to a piece of data :{}", JSON.toJSONString(o));
// Data stored in list,
objectList.add(o);
// achieve BATCH_COUNT 了 , Need to store the database once , Prevent tens of thousands of data in memory , Easy to OOM
if (objectList.size() >= BATCH_COUNT) {
saveData();
// Storage complete cleaning list
objectList.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// saveData();
log.info(" All data analysis completed ( You can do something else at this time )!");
}
/**
* Put in storage
*/
private void saveData() {
for (Object o : objectList) {
addressDao.insert((tAddressCity) o);
}
log.info("{} Data , Start storing the database !", objectList.size());
// This method is implemented by itself You can save the data and put it into storage
log.info(" Simulate database to save data :" + objectList);
}
public List<Object> getObjectList() {
return objectList;
}
public void setObjectList(List<Object> objectList) {
this.objectList = objectList;
}

Another version :
@ApiOperation(value = " Import a single sheet data ")
@PostMapping("/importSheet")
public void importSheet(@RequestParam("multipartFile") MultipartFile multipartFile) {
try {
InputStream inputStream = multipartFile.getInputStream();
// Read all asynchronously sheet data , Can be found in sheet Method parameter sheet Indexes ,sheet name
EasyExcel.read(inputStream, User.class, new UserDataListener(userService)).sheet().doRead();
} catch (IOException e) {
e.printStackTrace();
}
}
@ApiOperation(value = " Import multiple sheet data ")
@PostMapping("/importSheets")
public void importSheets(@RequestParam("multipartFile") MultipartFile multipartFile) {
ExcelReader excelReader = null;
try {
InputStream inputStream = multipartFile.getInputStream();
excelReader = EasyExcel.read(inputStream).build();
ReadSheet readSheet1 =
// structure ExcelReader object
EasyExcel.readSheet(0).head(User.class).registerReadListener(new UserDataListener(userService)).build();
ReadSheet readSheet2 =
// structure ExcelReader object
EasyExcel.readSheet(1).head(Achievement.class).registerReadListener(new AchievementDataListener(achievementService)).build();
// Note here Must put sheet1 sheet2 Pass it in together
excelReader.read(readSheet1, readSheet2);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (excelReader != null) {
// Don't forget to close it here , Temporary files will be created when reading , Then the disk will crash
excelReader.finish();
}
}
}
@ApiOperation(value = " Derived data ", produces = "application/octet-stream")
@PostMapping("/simpleWrite")
public void simpleWrite(HttpServletResponse response) {
userService.simpleWrite(response);
}
@ApiOperation(value = " Paging export data ", produces = "application/octet-stream")
@PostMapping("/pageWrite")
public void pageWrite(HttpServletResponse response) {
userService.pageWrite(response);
}
@ApiOperation(value = " Paging export multiple sheet data ", produces = "application/octet-stream")
@PostMapping("/pageWriteSheets")
public void pageWriteSheets(HttpServletResponse response) {
userService.pageWriteSheets(response);
}
@ApiOperation(value = " Paging export multiple sheet Data sending email ")
@PostMapping("/writeSendMail")
public void writeSendMail(HttpServletResponse response) throws IOException {
userService.writeSendMail(response);
}
}
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.easyexcel.dao.User;
import com.easyexcel.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Reading class of template
*/
public class UserDataListener extends AnalysisEventListener<User> {
private static final Logger LOGGER = LoggerFactory.getLogger(UserDataListener.class);
/**
* every other 3000 Storage database , Then clean up list , Convenient for memory recycling
*/
private static final int BATCH_COUNT = 3000;
List<User> list = new ArrayList<>();
private UserService userService;
/**
* If used spring, Please use this construction method . Each creation Listener You need to put spring The management class came in
*
* @param userService
*/
public UserDataListener(UserService userService) {
this.userService = userService;
}
@Override
public void invoke(User data, AnalysisContext context) {
LOGGER.info(" Parse to a piece of data :{}", JSON.toJSONString(data));
list.add(data);
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
LOGGER.info(" All data analysis completed !");
}
/**
* Plus the storage database
*/
private void saveData() {
LOGGER.info("{} Data , Start storing the database !", list.size());
userService.insertBatch(list);
LOGGER.info(" Storage database success !");
}
}
边栏推荐
- Transplantation method of MySQL UUID function in Dameng
- findfont: Font family [‘msyh‘] not found. Falling back to DejaVu Sans.
- Esayexcel quick start
- LabVIEW controls Arduino to realize infrared ranging (advanced chapter-6)
- I/o basic knowledge sorting
- Use of Python
- leetcode. 38 --- appearance series
- All in one 1258 Dynamic programming of digital pyramid problem solving
- 2. ZK's working mechanism
- 使用Jenkins的pipeline实现CI/CD
猜你喜欢

Form1 SLA光固化国产仿打印机用的切片软件PreForm下载

Iterator iterator, while loop, enhanced for loop usage

Recommend several books on Software Engineering

PT kill of MySQL

数字展厅设计方案的制定要注意这四点

Analysis: stable currency is not "stable currency", but a product in essence

下一代企业IT架构:云原生架构

R语言怎么利用ggplot2绘制QQ图和箱线图

R语言数据处理:tidyr包学习

mysql之pt-kill
随机推荐
SQL makes a column empty
A practice of encrypting server 3D model resources
Huawei machine test question: two sets output numbers within the distance
leetcode. 38 --- appearance series
qt制作简易的视频通话
【软件测试】多家大厂的软件测试面试常见问题合集(BAT、三大流量厂商、知名大厂)
How R language uses ggplot2 to draw QQ graph and box graph
Get started! How to quickly deploy web applications with dragon lab?
618 big promotion is in progress, Cloud Computing supports e-commerce live broadcast
618大促火熱進行中,雲計算力挺電商直播
The title of my composition is - "my district head father"
Zhangxiaobai teaches you how to use Ogg to synchronize Oracle 19C data with MySQL 5.7 (4)
[C language] C language programming: dynamic address book
Applet: get the current page routing information through getcurrentpages
Solving the problem of interval updating + interval maximum value by block sequence
[width first search] the shortest path in leetcode1091 binary matrix
10 个派上用场的 Flutter 小部件
19 r judgment control function exercise
Production of image cloud
[dry goods] typescript: extensions, infer and DVA type