springboot easypoi 实现excel 导出导入

easypoi官方文档:http://easypoi.mydoc.io/

https://blog.csdn.net/thinkingcao/article/details/85005930

1. pom

        <dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>3.2.0</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-web</artifactId>
			<version>3.2.0</version>
		</dependency>
		<dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-annotation</artifactId>
			<version>3.2.0</version>
		</dependency>

2. 定义需要导出的实体对象User


@ExcelTarget("20")
@Setter
@Getter
@ToString
public class User implements java.io.Serializable{
	@Excel(name = "id", width=15)
	@NotBlank(message = "该字段不能为空")
	private Integer id;
 
	@Excel(name = "姓名", orderNum = "0", width=30)
	private String name;
 
	@Excel(name = "性别", replace = { "男_1", "女_2" }, orderNum = "1", width=30)
	private String sex;
 
	@Excel(name = "生日", exportFormat = "yyyy-MM-dd",  orderNum = "2", width=30)
	private String birthday;
 

3. Excel导入导出工具类

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;
 
//Excel导入导出工具类
public class ExcelUtils {
	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());
			System.out.println(e.getMessage());
		}
		return list;
	}
 
}
@Service
public class UserService {
	
	public List<User> findAll() {
		List<User> listAll = Lists.newArrayList();
		List<User> list = Lists.newArrayList();
		User user = new User();
		user.setId(10);
		user.setName("张三");
		user.setSex("男");
		user.setBirthday(new Date().toString());
		User user1 = new User();
		user1.setId(20);
		user1.setName("李四");
		user1.setSex("男");
		user1.setBirthday(new Date().toString());
		user.setBirthday(new Date().toString());
		User user2 = new User();
		user2.setId(20);
		user2.setName("王五");
		user2.setSex("男");
		user2.setBirthday(new Date().toString());
		list.add(user);
		list.add(user1);
		list.add(user2);
		listAll.addAll(list);
		return listAll;
	}
}
import java.util.List;
 
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.thinkingcao.demo.easypoi.entity.User;
import com.thinkingcao.demo.easypoi.service.UserService;
import com.thinkingcao.demo.easypoi.utils.ExcelUtils;
 
/**
 * <pre>
 * &#64;author cao_wencao
 * &#64;date 2018年12月13日 下午6:16:59
 * </pre>
 */
@RestController
@RequestMapping("/excel/export")
public class ExcelExportController {
	@Autowired
	private UserService userService;
 
	@GetMapping("/exportExcel")
	public void export(HttpServletResponse response) {
		System.out.println(1);
		// 模拟从数据库获取需要导出的数据
		List<User> personList = userService.findAll();
		// 导出操作
		ExcelUtils.exportExcel(personList, "easypoi导出功能", "导出sheet1", User.class, "测试user.xls", response);
 
	}

8. 导入方法的Controller。ExcelImportController 

@RestController
@RequestMapping("/excel/import")
@Slf4j
public class ExcelImportController {
 
	@PostMapping("/importExcel")
	public String importExcel2(@RequestParam("file") MultipartFile file) {
		ImportParams importParams = new ImportParams();
		// 数据处理
		importParams.setHeadRows(1);
		importParams.setTitleRows(1);
		// 需要验证
		importParams.setNeedVerfiy(false);       
        
		try {
			ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
					importParams);
			List<User> userList = result.getList();
			for (User User : userList) {
				// System.out.println(User);
				log.info("从Excel导入数据到数据库的详细为 :{}", JSONObject.toJSONString(User));
				//TODO 将导入的数据做保存数据库操作
			}
			log.info("从Excel导入数据一共 {} 行 ", userList.size());
		} catch (IOException e) {
			log.error("导入失败:{}", e.getMessage());
		} catch (Exception e1) {
			log.error("导入失败:{}", e1.getMessage());
		}
		return "导入成功";
	}
}

 问题: 报错 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

开始 controller 方法写的是    

    @RequestMapping( value = "/add", method = RequestMethod.POST )

    public String add( @RequestBody Map<String, Object> params ) {   

改成

    @RequestMapping( value = "/add", method = RequestMethod.POST )

    public String add( @RequestParam Map<String, Object> params ) {

就不报错了。
 

问题:导出报错

1.千万别去合并单元格,除非是已知的内容(自己写的)
2.设置样式后,所设置的样式行数一定要大于集合的长度
99.99%出错的人都在这是去合并单元格了的

 

 

展开阅读全文

没有更多推荐了,返回首页