在Excel文件導入過程中實際上有兩個問題 (採用apche poi的方式)
* xls的文件限制了不能一次性導出65536條數據
* 實際過程中Excel文件的解析有可能會造成內存溢出的問題
* mybatis(mysql)批量導入數據性能過差
內存泄漏:是指申請的內存空間無法正常被收回,造成“無用又不可收回”的狀況內存溢出:指程序在申請內存空間時,已經沒有足夠的內存空間被使用。(內存泄漏通常是內存溢出的主要原因)針對上述的問題,需要對項目進一步地優化:
1. 文件上傳到服務器的請求方式使用ftp而不是http
2. 儘可能減少遍歷的次數
3. 使用StringBuffer而不是String (並且StringBuffer相對於StringBuilder線程安全的)
4. 使用FileWriter寫入文件時要要一次寫入,減少IO讀寫次數
5. 採用多線程的方式去批量地提交事務 (補充 提供List.subList(開始index,結束index)的方式截取集合,或者採用流式表達式的方式進行切分)https://blog.csdn.net/FKJGFK/article/details/104004216
6. mysql數據庫不能同時支持30萬數據的 一次性事務提交,需要分批次地去進行事務的提交,否則數據將堆積到mysql數據庫中,導致數據庫性能過低。(需要採用編程式事務的方式分批次多次提交)
方式一:優化內存
針對內存溢出的情況我們做以下調整:
1.提高了編譯器的jvm的空間 -Xms128m -Xmx1700m (在項目的啓動腳本中 nohup -Xms128m -Xmx1700m -jar 包名 & )
2.創建Workbook 藉助xlsx-streamer(StreamingReader) 來創建一個緩衝區域批量地讀取文件 (不會將整個文件實例化到對象當中)
依賴
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>xlsx-streamer</artifactId>
<version>2.1.0</version>
</dependency>
實現方式
public List<AddressBookPojo> importExcelxlsx( String tmpFile ) {
List<AddressBookPojo> list = new ArrayList<AddressBookPojo>();
FileInputStream in=null;
try {
in = new FileInputStream(tmpFile);
Workbook wk = StreamingReader.builder()
.rowCacheSize(1000) //緩存到內存中的行數,默認是10
.bufferSize(8192) //讀取資源時,緩存到內存的字節大小,默認是1024
.open(in); //打開資源,必須,可以是InputStream或者是File,注意:只能打開XLSX格式的文件
Sheet sheet = wk.getSheetAt(0);
int i =0;
for (Row row : sheet) {
i++;//從第2行開始取數據,默認第一行是表頭.
if(i==1)
continue;
AddressBookPojo abp = new AddressBookPojo();
//遍歷所有的列
int j=0;
for (Cell cell : row) {
switch (j) {
case 0 :abp.setName(cell.getStringCellValue());break;
case 1 :abp.setFristDepartName(cell.getStringCellValue());break;
/**這裏省略其他的屬性**/
default: break;
}
j++;
}
list.add(abp);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
IOUtils.closeQuietly(in);
}
return list;
}
方式二:EasyExcel
EasyExcel是阿里的引用了apache poi,所以不能再引用apache poi的依賴。
使用lombok可以簡化Excel對POJO的綁定關係。
依賴
<!--easyExcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<optional>true</optional>
</dependency>
工具類
package com.xiyuan.startingpoint.utils;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @description:
* @author: chenmingjian
* @date: 19-3-18 16:16
*/
@Slf4j
public class ExcelUtil {
private static Sheet initSheet;
static {
initSheet = new Sheet(1, 0);
initSheet.setSheetName("sheet");
//設置自適應寬度
initSheet.setAutoWidth(Boolean.TRUE);
}
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
// throw new NormalException(e.getMessage());
}
}
/**
* 讀取少於1000行數據
* @param filePath 文件絕對路徑
* @return
*/
public static List<Object> readLessThan1000Row(String filePath){
return readLessThan1000RowBySheet(filePath,null);
}
/**
* 讀小於1000行數據, 帶樣式
* filePath 文件絕對路徑
* initSheet :
* sheetNo: sheet頁碼,默認爲1
* headLineMun: 從第幾行開始讀取數據,默認爲0, 表示從第一行開始讀取
* clazz: 返回數據List<Object> 中Object的類名
*/
public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
return EasyExcelFactory.read(fileStream, sheet);
} catch (FileNotFoundException e) {
log.info("找不到文件或文件路徑錯誤, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.info("excel文件讀取失敗, 失敗原因:{}", e);
}
}
return null;
}
/**
* 讀大於1000行數據
* @param filePath 文件覺得路徑
* @return
*/
public static List<Object> readMoreThan1000Row(String filePath){
return readMoreThan1000RowBySheet(filePath,null);
}
/**
* 讀大於1000行數據, 帶樣式
* @param filePath 文件覺得路徑
* @return
*/
public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet){
if(!StringUtils.hasText(filePath)){
return null;
}
sheet = sheet != null ? sheet : initSheet;
InputStream fileStream = null;
try {
fileStream = new FileInputStream(filePath);
ExcelListener excelListener = new ExcelListener();
EasyExcelFactory.readBySax(fileStream, sheet, excelListener);
return excelListener.getDatas();
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
}finally {
try {
if(fileStream != null){
fileStream.close();
}
} catch (IOException e) {
log.error("excel文件讀取失敗, 失敗原因:{}", e);
}
}
return null;
}
/**
* 生成excle
* @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 數據源
* @param head 表頭
*/
public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head){
writeSimpleBySheet(filePath,data,head,null);
}
/**
* 生成excle
* @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 數據源
* @param sheet excle頁面樣式
* @param head 表頭
*/
public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet){
sheet = (sheet != null) ? sheet : initSheet;
if(head != null){
List<List<String>> list = new ArrayList<>();
head.forEach(h -> list.add(Collections.singletonList(h)));
sheet.setHead(list);
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write1(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件導出失敗, 失敗原因:{}", e);
}
}
}
/**
* 生成excle
* @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 數據源
*/
public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data){
writeWithTemplateAndSheet(filePath,data,null);
}
/**
* 生成excle
* @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param data 數據源
* @param sheet excle頁面樣式
*/
public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet){
if(CollectionUtils.isEmpty(data)){
return;
}
sheet = (sheet != null) ? sheet : initSheet;
sheet.setClazz(data.get(0).getClass());
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
writer.write(data,sheet);
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件導出失敗, 失敗原因:{}", e);
}
}
}
/**
* 生成多Sheet的excle
* @param filePath 絕對路徑, 如:/home/chenmingjian/Downloads/aaa.xlsx
* @param multipleSheelPropetys
*/
public static void writeWithMultipleSheel(String filePath,List<MultipleSheelPropety> multipleSheelPropetys){
if(CollectionUtils.isEmpty(multipleSheelPropetys)){
return;
}
OutputStream outputStream = null;
ExcelWriter writer = null;
try {
outputStream = new FileOutputStream(filePath);
writer = EasyExcelFactory.getWriter(outputStream);
for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {
Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;
if(!CollectionUtils.isEmpty(multipleSheelPropety.getData())){
sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());
}
writer.write(multipleSheelPropety.getData(), sheet);
}
} catch (FileNotFoundException e) {
log.error("找不到文件或文件路徑錯誤, 文件:{}", filePath);
}finally {
try {
if(writer != null){
writer.finish();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
log.error("excel文件導出失敗, 失敗原因:{}", e);
}
}
}
/*********************匿名內部類開始,可以提取出去******************************/
@Data
public static class MultipleSheelPropety{
private List<? extends BaseRowModel> data;
private Sheet sheet;
}
/**
* 解析監聽器,
* 每解析一行會回調invoke()方法。
* 整個excel解析結束會執行doAfterAllAnalysed()方法
*
* @author: chenmingjian
* @date: 19-4-3 14:11
*/
@Getter
@Setter
public static class ExcelListener extends AnalysisEventListener {
private List<Object> datas = new ArrayList<>();
/**
* 逐行解析
* object : 當前行的數據
*/
@Override
public void invoke(Object object, AnalysisContext context) {
//當前行
// context.getCurrentRowNum()
if (object != null) {
datas.add(object);
}
}
/**
* 解析完所有數據後會調用該方法
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//解析結束銷燬不用的資源
}
}
/************************匿名內部類結束,可以提取出去***************************/
}
POJO
/**
* 用戶Pojo
*/
@Data
@TableName("tb_user")
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserInfoPojo extends CommentPojo{
private static final long serialVersionUID = 1L;
//解決mybatis-plus和easyExcel的衝突問題
@JsonIgnoreProperties(ignoreUnknown = true)
@TableField(exist = false)
private Map<Integer,CellStyle> cellStyleMap = new HashMap<Integer, CellStyle>();
@TableId(type = IdType.UUID)
private String id; //主鍵
@TableField("user_name")
@ExcelProperty(value = "用戶名(必填)", index = 0)
private String userName; //用戶名
@ExcelProperty(value = "密碼(必填)", index = 1)
private String password;//密碼
}
Excel導入
/**
* 導入Excel
*
* @param file
* @param username
* @return
*/
@Override
public ResponseResult importExcel(MultipartFile file, String username) throws Exception {
String tempfilePath = null;
File tempfile = null;
FileWriter fw = null;
try {
//第一步:創建臨時文件
String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
tempfilePath = tempPath + CommonUtil.getUUID() + "." + fileType;
tempfile = new File(tempfilePath);
file.transferTo(tempfile);
List<Object> objects = ExcelUtil.readMoreThan1000Row(tempfilePath);
//第二步:進行Excel文件校驗
ResponseResult responseResult = checkExcel(objects,username);
if (responseResult.getSuccess()) {//List讀取成功
List<UserInfoPojo> list = (List<UserInfoPojo>) responseResult.getValue();
insertBatch(list);
return ResponseResult.success(ConstantsUtil.OPERATE_SUCCESS);
} else {//讀取失敗
String errortempFile = tempPath +"/"+username+ "/user/" + CommonUtil.getUUID() + ".txt";
File file1 = new File(errortempFile);
fw = new FileWriter(errortempFile);
fw.write(responseResult.getMessage());
responseResult.setValue(errortempFile);
return responseResult;
}
} catch (IOException e) {
logger.error("用戶模塊導入失敗" + e.getMessage(), e);
return ResponseResult.error(ConstantsUtil.OPERATE_ERROR);
} finally {
if(fw !=null)
fw.close();
FileUtils.deleteQuietly(tempfile);
}
}
private ResponseResult checkExcel(List<Object> objects,String username) throws Exception {
List<UserInfoPojo> userInfoPojos = new ArrayList<>();
StringBuffer bf = new StringBuffer();
if (objects != null && objects.size() > 1) {
int i = 2;
for (int j = 1; j < objects.size(); j++) {
List<String> list = (List<String>) objects.get(j);
if(list.size()<2){
bf.append("第" + i + "行中的存在大量必填項未填寫,請檢查" + newLine);
continue;
}
UserInfoPojo userInfoPojo = new UserInfoPojo();
userInfoPojo.setId(CommonUtil.getUUID());
userInfoPojo.setUpdater(username);
userInfoPojo.setUpdateTime(new Date());
if (StringUtils.isBlank(list.get(0))) {
bf.append("第" + i + "行中的用戶名爲必填項不得爲空" + newLine);
} else {
userInfoPojo.setUserName(list.get(0));
}
if (StringUtils.isBlank(list.get(1))) {
bf.append("第" + i + "行中的密碼爲必填項不得爲空" + newLine);
} else {
userInfoPojo.setPassword(list.get(1));
}
userInfoPojos.add(userInfoPojo);
i++;
}
}
if (bf.length() > 0) {//導入失敗
return ResponseResult.error(bf.toString());
} else {//導入成功
return ResponseResult.success(userInfoPojos, ConstantsUtil.OPERATE_SUCCESS);
}
}
Excel導出
/**
* Excel文件導入
*
* @param list
* @return
*/
@Override
public String exportExcel(List<UserInfoPojo> list) throws Exception {
String tempfile = tempPath + CommonUtil.getUUID() + ".xlsx";
ExcelUtil.writeWithTemplate(tempfile, list);
return tempfile;
}