近期完成了后管系統(tǒng)報(bào)表的導(dǎo)入導(dǎo)出藻烤,完成之后做下總結(jié)
1绷雏、首先我們對(duì)采用的插件進(jìn)行了篩選,最后選擇EasyPoi怖亭,用的人也很多涎显,算是對(duì)poi的簡(jiǎn)單封裝
這里項(xiàng)目用的springboot,所以只用pom引入配置即可
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.0.3</version>
</dependency>
2兴猩、根據(jù)配置編寫(xiě)實(shí)體類(lèi)
先簡(jiǎn)單介紹一下關(guān)于@Excel注解的一些常用屬性
name:列名
orderNum:第幾列
replace:值得替換 例:replace = {"身份證_1"} 數(shù)據(jù)庫(kù)值為"1"期吓,導(dǎo)出時(shí)會(huì)自動(dòng)被"身份證"代替
@Excel(name = "姓名", orderNum = "0")
private String name;
@Excel(name = "證件類(lèi)型", replace = {"身份證_1"}, orderNum = "1")
private String identifyType;
@Excel(name = "證件號(hào)碼", orderNum = "2")
private String identifyNo;
@Excel(name = "手機(jī)號(hào)1", orderNum = "3")
private String phoneA;
@Excel(name = "手機(jī)號(hào)2", orderNum = "4")
private String phoneB;
@Excel(name = "手機(jī)號(hào)3", orderNum = "5")
private String phoneC;
@Excel(name = "固定電話", orderNum = "6")
private String telephone;
@Excel(name = "電子郵箱", orderNum = "7")
private String email;
@Excel(name = "身份證地址", orderNum = "8")
private String idcardAdress;
@Excel(name = "戶籍地址", orderNum = "9")
private String householdAddress;
@Excel(name = "居住地址", orderNum = "10")
private String liveAddress;
@Excel(name = "工作地址", orderNum = "11")
private String workAddress;
3、整合導(dǎo)入導(dǎo)出方法
package com.***.common;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
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;
public class FileWithExcelUtil {
private static final Logger log = LoggerFactory.getLogger(FileWithExcelUtil .class);
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) {
log.error("[monitor][IO][表單功能]", e);
}
}
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 e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
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 e;
} catch (Exception e) {
e.printStackTrace();
log.error("[monitor][表單功能]", e);
}
return list;
}
}
4倾芝、導(dǎo)出操作
/**
* 導(dǎo)出模版
* @param response
*/
@RequestMapping("/exportExcel/model")
public ResponseModel export(HttpServletResponse response){
try {
//模擬從數(shù)據(jù)庫(kù)獲取需要導(dǎo)出的數(shù)據(jù)
List<CustomerList> personList = new ArrayList<>();
FileWithExcelUtil.exportExcel(personList,"客戶信息表","客戶表",CustomerList.class,"客戶表.xls",response);
return ResponseModel.success("操作成功");
} catch (Exception e) {
logger.info("getCustomerPage", e);
return ResponseModel.fail("導(dǎo)出模版失敗");
// TODO: handle exception
}
}
5讨勤、導(dǎo)入操作
將導(dǎo)入的模版數(shù)據(jù)拿到,填充到自己要使用的實(shí)體類(lèi)
ps:導(dǎo)入的數(shù)據(jù)模版一般都是平鋪的晨另,而我們的實(shí)體類(lèi)一般都有層次潭千,所以我們的excel模版實(shí)體往往不是我們數(shù)據(jù)庫(kù)對(duì)應(yīng)的bean,需要我們將其自行填充
/**
* 導(dǎo)入excel
*/
@RequestMapping(value = "/importExcelForType", method = RequestMethod.POST)
public ResponseModel importExcel(@RequestParam("file") MultipartFile file,String customerType){
try {
// String filePath = "/Users/***/Downloads/response.xls";
//解析excel借尿,
// List<CustomerList> personList = FileWithExcelUtil.importExcel(filePath, 1, 1, CustomerList.class);
List<CustomerList> personList = FileWithExcelUtil.importExcel(file, 1, 1, CustomerList.class);
//也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)導(dǎo)入
System.out.println("導(dǎo)入數(shù)據(jù)一共【"+personList.size()+"】行");
for (int i = 0; i < personList.size(); i++) {
CustomerList excel = personList.get(i);
CmCustomerForExcel customer = customerListByExcel(excel);
customer.setCustomerType(customerType);
customerService.saveExcelList(customer);
}
logger.info(personList.toString());
return ResponseModel.success("操作成功");
} catch (Exception e) {
// TODO: handle exception
logger.error(e.toString());
return ResponseModel.fail("導(dǎo)入失敗");
}
補(bǔ)充
高級(jí)用法可參考EasyPoi的官方文檔:http://easypoi.mydoc.io