springboot 实现后端接口操作Excel的导出、批量导入功能
2020-12-17 19:35
标签:ice source collect values title value EDA 格式化 mybatis 本文操作Excel使用的是poi方式 springboot 实现后端接口操作Excel的导出、批量导入功能 标签:ice source collect values title value EDA 格式化 mybatis 原文地址:https://www.cnblogs.com/personblog/p/14103752.html
dependency>
groupId>org.apache.poigroupId>
artifactId>poiartifactId>
version>RELEASEversion>
dependency>
dependency>
groupId>org.apache.poigroupId>
artifactId>poi-ooxmlartifactId>
version>RELEASEversion>
dependency>
package com.xj.demo.common;
import com.xj.demo.model.Request.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.*;
/**
* Excel 工具类
* **/
@Slf4j
public class ExcelUtil {
/**
* 方法名:exportExcel
* 功能:导出Excel
*/
public static void exportExcel(HttpServletResponse response, ExcelData data) {
log.info("导出解析开始,fileName:{}",data.getFileName());
try {
//实例化HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个Excel表单,参数为sheet的名字
HSSFSheet sheet = workbook.createSheet("sheet");
//设置表头
setTitle(workbook, sheet, data.getHead());
//设置单元格并赋值
setData(sheet, data.getData());
//设置浏览器下载
setBrowser(response, workbook, data.getFileName());
log.info("导出解析成功!");
} catch (Exception e) {
log.info("导出解析失败!");
e.printStackTrace();
}
}
/**
* setTitle设置标题
* */
private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
try {
HSSFRow row = sheet.createRow(0);
//设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
for (int i = 0; i ) {
sheet.setColumnWidth(i, 15 * 256);
}
//设置为居中加粗,格式化时间格式
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//创建表头名称
HSSFCell cell;
for (int j = 0; j ) {
cell = row.createCell(j);
cell.setCellValue(str[j]);
cell.setCellStyle(style);
}
} catch (Exception e) {
log.info("导出时设置表头失败!");
e.printStackTrace();
}
}
/**
* 方法名:setData
* 功能:表格赋值
*/
private static void setData(HSSFSheet sheet, List
package com.xj.demo.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
public class FileUtil {
private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);
public static String uploadFile(MultipartFile multipartFile) throws Exception {
String fileName = UUID.randomUUID().toString() + ".xls";
String path = ResourceUtils.getURL("classpath:").getPath() + "static/upload/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
String fileFullPath = path + fileName;
logger.info("fileFullPath:" + fileFullPath);
InputStream inputStream = null;
FileOutputStream fos = null;
try {
inputStream = multipartFile.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
fos = new FileOutputStream(fileFullPath);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fos);
int size = multipartFile.getBytes().length;
byte[] buffer = new byte[1024];// 一次读多个字节
while ((size = inputStream.read(buffer, 0, buffer.length)) != -1) {
fos.write(buffer, 0, buffer.length);
}
} catch (Exception ex) {
logger.error("ex:" + ex.getMessage());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (fos != null) {
fos.close();
}
}
return fileFullPath;
}
/*
* 获取文件扩展名 小写
* */
public static String getFileExt(String fileName) {
String ext = "";
try {
if (!fileName.equals("")) {
ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
}
} catch (Exception e) {
ext = "";
}
return ext;
}
}
@ApiOperation("导出用户信息")
@PostMapping("/exportuserinfo")
public Result ExportUserInfo(@RequestBody User_InfoListRequest userInfo) {
try {
logger.info("user/exportuserinfo:");
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = requestAttributes.getResponse();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
userInfo.pageSize = 10000;//导出最大1W条
List
insert id="addBatchUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.xj.demo.model.Request.UserBatchRequest">
insert into user_info
(id,uname,uage,create_time)
values
foreach collection="list" item="user" index="index" separator=",">
(#{user.id,jdbcType=VARCHAR}, #{user.uname,jdbcType=VARCHAR}, #{user.uage,jdbcType=INTEGER},
#{user.create_time,jdbcType=TIMESTAMP})
foreach>
insert>
@Override
public int addBatchUser(List
@ApiOperation("导入用户信息")
@PostMapping("/inportuserinfo")
public Result InportUserInfo(@RequestParam("file") MultipartFile multipartFile) throws Exception {
try {
logger.info("user/inportuserinfo:");
String[] extObjs={".xls",".xlsx"};
String fileName = multipartFile.getOriginalFilename();
String ext = FileUtil.getFileExt(fileName);
if (!Arrays.asList(extObjs).contains(ext))
return Result.FAIL("文件为空或文件格式不正确!");
String path = FileUtil.uploadFile(multipartFile);
List
上一篇:JAVA基础 IO流三 功能流?
下一篇:java-jdk环境配置
文章标题:springboot 实现后端接口操作Excel的导出、批量导入功能
文章链接:http://soscw.com/index.php/essay/36923.html