在我们日常研发工作中很多的地方需要用到导入导出excel的功能,在这里我将需要的代码进行总结方便自己也方便别人。
一、导出篇:
1.首先我们需要pom文件中配置上需要的maven包
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.0</version>
</dependency>
2.第二步我们需要写一个导出文件的工具类
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
public class FileUtils {
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
if (workbook != null) ;
downLoadExcel(fileName, response, workbook);
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
//throw new NormalException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null) ;
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
// throw new NormalException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
// throw new NormalException(e.getMessage());
}
return list;
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (NoSuchElementException e) {
// throw new NormalException("excel文件不能为空");
} catch (Exception e) {
// throw new NormalException(e.getMessage());
}
return list;
}
}
3.第三步这一步我们就可以将查询出来的列表数据导出到excel文件中
首先我们需要建一个和excel表头文件对应的对象
public class Smart implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@Excel(name = "名称",needMerge =true,width = 30)
private String name;
@Excel(name = "负责人",needMerge =true,width = 30)
private String person;
@Excel(name = "联系方式",needMerge =true,width = 30)
private String contactMode;
@Excel(name = "详细地址",needMerge =true,width = 60)
private String detailedAddress;
@Excel(name = "介绍",needMerge =true,width = 60)
private String introduce;
}
建好对象后我们就可以将列表查询出来的数据导出了,这里需要调用工具类的方法进行导出。
public void getExportSmarList(String partyname, String person, String regionCode, String contactMode, HttpServletResponse response) {
//查询对应的集合
List<Smart> smartList = baseMapper.getSmartList(name, person, regionCode, contactMode);
//调用工具类进行导出
FileUtils.exportExcel(smartList,"excel文件中的名称","", Smart.class,"名称.xls",response);
}
二、导入篇
方式一:利用excel表头的顺序进行导入
1.pom文件需要的maven包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>${poi.version}</version>
</dependency>
2.导入需要的工具类
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class ImportExcelUtils {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName
* @return
* @throws Exception
*/
public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = ImportExcelUtils.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(ImportExcelUtils.getCellValue(cell));
}
list.add(li);
}
}
// work.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName
* @return
* @throws Exception
*/
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
// DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
if (cell!=null){
switch (cell.getCellType()) {
case STRING:
value = cell.getRichStringCellValue().getString();
break;
case NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}
else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}
else{
value = sdf.format(cell.getDateCellValue());
}
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case BLANK:
value = "";
break;
default:
break;
}
}
return value;
}
}
3.导入时从excel文件中进行读取数据,读取完毕后进行批量导入
public ResponseResult importPartyOrg(MultipartFile file) {
Map<String,Object> resultMap = new HashMap<>();
List<Smart> tbZbzsList = new ArrayList<>();
boolean saveBatch = false;
try {
//验证文件类型
if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")&&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
resultMap.put("mete", "文件类型有误!请上传Excle文件");
throw new Exception("文件类型有误!请上传Excle文件");
}
//根据工具类获取数据
List<List<Object>> olist = ImportExcelUtils.getListByExcel(file.getInputStream(), file.getOriginalFilename());
resultMap.put("导入成功",200);
//封装数据
for (int i = 0; i < olist.size(); i++) {
List<Object> list = olist.get(i);
Smart tbZbzs = new Smart();
//根据下标获取每一行的每一条数据
tbZbzs.setCode(UUID.randomUUID().toString().replaceAll("-",""));
tbZbzs.setPartyOrgName(String.valueOf(list.get(0)));
tbZbzs.setPartyOrgPerson(String.valueOf(list.get(1)));
tbZbzs.setContactMode(String.valueOf(list.get(2)));
tbZbzsList.add(tbZbzs);
}
saveBatch = this.saveBatch(tbZbzsList);
} catch (Exception e) {
e.printStackTrace();
}
if(saveBatch){
return ResponseResult.ok(saveBatch);
}else {
return ResponseResult.error("导入失败");
}
}
此方法中如果表中有空数据可能会导致位置发生变化影响导入的结果。
方式二:在对象实体中注明excel表头的下标位置
1.pom文件中的内容
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.1</version>
</dependency>
2.调用工具类进行导入
if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")&&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
resultMap.put("mete", "文件类型有误!请上传Excle文件");
throw new Exception("文件类型有误!请上传Excle文件");
}
InputStream inputStream = file.getInputStream();
List<BaseEventSaveImport> list1 = EasyExcel.read(inputStream) //调用read方法
.head(BaseEventSaveImport.class) //对应导入的实体类
.sheet(0) //导入数据的sheet页编号,0代表第一个sheet页,如果不填,则会导入所有sheet页的数据
.headRowNumber(1) //列表头行数,1代表列表头有1行,第二行开始为数据行
.doReadSync(); //开始读Excel,返回一个Li
resultMap.put("导入成功",200);
导入推荐使用第二种方式进行