org.apache.poi
poi-scratchpad
3.14
org.apache.poi
poi-ooxml
3.14
org.apache.poi
poi-ooxml-schemas
3.14
org.apache.poi
ooxml-schemas
1.3
excelpoi:
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelPoi {
private static Logger log = Logger.getLogger(ExcelPoi.class);
/**
* 导出数据
*
* @param response
* @param list
* @param titles
* @param filename
* @throws IOException
*/
public static void exportObject(HttpServletResponse response,List> list, String[] titles, String filename) throws IOException {
response.setCharacterEncoding("utf-8");
response.setHeader("content-disposition", "attachment;filename=" + new String((filename + System.currentTimeMillis()).getBytes(), "ISO8859-1") + ".xls");
try (Workbook workbook = new HSSFWorkbook(); OutputStream ops = response.getOutputStream()) {
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 20);
font.setColor(HSSFFont.COLOR_RED);
font.setFontName("黑体");
font.setBold(false);
font.setItalic(false);
Sheet sheet = workbook.createSheet(filename);
Row titleRow = sheet.createRow(0);
for (int column = 0; column < titles.length; column++) {
Cell itemCell = titleRow.createCell(column);
itemCell.setCellValue(titles[column]);
}
if (!ParamCheck.isListEmpty(list)) {
for (int i = 0; i < list.size(); i++) {
Row row = sheet.createRow(i + 1);
createRow(row, titles, list.get(i));
// System.out.println("list.get(i)"+list.get(i));
}
}
for (int column = 0; column < titles.length; column++) {
sheet.autoSizeColumn(column);
}
workbook.write(ops);
} catch (Exception e) {
log.error(e);
}
}
private static void createRow(Row row, String[] titles, Object object) {
for (int j = 0; j < titles.length; j++) {
Field[] publicFields = object.getClass().getFields();
Field[] declaredFields = object.getClass().getDeclaredFields();
fieldToCell(object, publicFields, titles, row);
fieldToCell(object, declaredFields, titles, row);
}
}
/**
* 获取对象属性填充到表格一条数据
*
* @param object
* @param fields
* @param titles
* @param row
*/
private static void fieldToCell(Object object, Field[] fields, String[] titles, Row row) {
for (Field field : fields) {
if (field.isAnnotationPresent(ExcelTitle.class)) {
Object value = MyObjectUtils.getFieldValueByName(object, field);
ExcelTitle excelTitle = field.getAnnotation(ExcelTitle.class);
String title = excelTitle.title();
int index = MyArrayUtils.getIndex(titles, title);
if (index != -1 && value != null) {
Cell cell = row.createCell(index);
cell.setCellValue("" + value);
}
}
}
}
/**
* 导入数据
*
* @param file
* @param fileName
* @param clz
* @throws Exception
*/
public List importObjectList(InputStream file, String fileName, Class clz) throws Exception {
List list = new ArrayList<>();
Workbook workbook = null;
if (fileName.endsWith("xls")) {
workbook = new HSSFWorkbook(file);
} else if (fileName.endsWith("xlsx")) {
workbook = new XSSFWorkbook(file);
}
file.close();
if (workbook != null) {
// Map titleMap = new HashMap<>();
Map
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 字段校验注解
*
* @author zhz
* @date 2019年12月02日
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface ExcelTitle {
String title();
String dataMap() default "";
}
MessageUtils:
public class MessageUtils {
public static final String SUCCESS = "SUCCESS";
public static final String FAIL = "FAIL";
public static final String ERROR = "ERROR";
private MessageUtils() {
}
}
MyArrayUtils:
public class MyArrayUtils {
private MyArrayUtils() {
}
public static int getIndex(Object[] objs, Object object) {
int index = -1;
for (int i = 0; i < objs.length; i++) {
Object obj = objs[i];
if (obj.equals(object)) {
return i;
}
}
return index;
}
}
MyObjectUtils:
import org.apache.log4j.Logger;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class MyObjectUtils {
private static Logger log = Logger.getLogger(MyObjectUtils.class);
private MyObjectUtils() {
}
/**
* 通过属性名称获取属性值
*
* @param object
* //@param fieldName
* @return
*/
public static Object getFieldValueByName(Object object, Field field) {
try {
String fieldName = field.getName();
StringBuilder sb = new StringBuilder();
sb.append("get");
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
Method method = object.getClass().getMethod(sb.toString());
return method.invoke(object);
} catch (Exception e) {
log.info("获取字段值异常" + e);
return MessageUtils.ERROR;
}
}
/**
* 通过属性名称给对象赋值
*
* @param object
* //@param fieldName
* @param value
* @return
*/
public static Object setFieldValueByName(Object object, Field field, Object value) {
try {
String fieldName = field.getName();
System.out.println("fieldName: "+fieldName);
Class>[] paramTypes = new Class[1];
paramTypes[0] = field.getType();
StringBuilder sb = new StringBuilder();
sb.append("set");
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
Method method = object.getClass().getMethod(sb.toString(), paramTypes);
System.out.println("object: "+object);
System.out.println("value:"+value+" "+value.getClass());
return method.invoke(object, value);
} catch (Exception e) {
log.error("赋值异常" + e);
return MessageUtils.ERROR;
}
}
}
ParamCheck:
import java.util.List;
public class ParamCheck {
private ParamCheck() {
}
/**
* 校验参数是否为空
*
* @param args
* @return
*/
public static boolean checkParamIsEmpty(Object... args) {
for (Object param : args) {
if (param == null) {
return true;
}
if (param instanceof String && "".equals(param)) {
return true;
}
if (param instanceof Integer && 0 == (int) param) {
return true;
}
}
return false;
}
/**
* 校验参数是否全部为空
*
* @param args
* @return
*/
public static boolean checkParamIsAllEmpty(Object... args) {
for (Object param : args) {
if (param != null) {
boolean flag = false;
if (param instanceof String && "".equals(param)) {
flag = true;
}
if (param instanceof Integer && 0 == (int) param) {
flag = true;
}
if (!flag) {
return false;
}
}
}
return true;
}
/**
* 校验字符串是否为空
*
* @param str
* @return
*/
public static boolean isStringEmpty(String str) {
return str == null || "".equals(str);
}
/**
* 校验数字是否为空
*
* @param str
* @return
*/
public static boolean isIntEmpty(Integer number) {
return number == null || number == 0;
}
/**
* 校验集合是否为空
*
* @param str
* @return
*/
public static boolean isListEmpty(List> list) {
return list == null || list.isEmpty();
}
}
要在bean类里面为每一个属性添加@ExcelTitle(title = “xx”),xx是excel的title,由你自己决定。
添加完上面的工具类后,下面是导入导出的例子:
User:
@ExcelTitle(title = "id")
private Integer id;
@ExcelTitle(title = "用户名")
private String username;
@ExcelTitle(title = "password")
private String password;
@ExcelTitle(title = "sex")
private String sex;
@ExcelTitle(title = "jurisdiction")
private Integer jurisdiction;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username=" + username +
", password=" + password +
", sex=" + sex +
", jurisdiction=" + jurisdiction +
'}';
}
//下面的get和set方法就不贴了
导入:
@RequestMapping(value = "/importCustomerList",method = RequestMethod.POST, produces = "text/html;charset=UTF-8;")
@ResponseBody
public String importCustomerList(@RequestParam("file") MultipartFile file, HttpSession session,HttpServletRequest request) {
String statis="02";//导入失败
try {
if (file == null || file.getSize() == 0 || !file.getOriginalFilename().contains(".xls")) {
return "文件无效";
}
//根据自己定义的实体类更换list的泛型
List list = new ExcelPoi().importObjectList(file.getInputStream(), file.getOriginalFilename(), User.class);
//User可以替换成你的实体类
//list就是获取的数据
Iterator iterator=list.iterator();
while (iterator.hasNext())
{
User user=(User)iterator.next();
//可以在这里添加方法判断要导入的数据是否符合要求
userService.insertSelective(user);//插入语句
}
} catch (Exception e) {
//log.error(e);
e.printStackTrace();
}
return statis;
}
导出:
@RequestMapping(value = "/User.html/exportUserAllList", produces = "text/html;charset=UTF-8;")
@ResponseBody
public String exportCustomerList(HttpServletResponse response, String search) {
try {
List date = userService.findAll();
//customService.getCustomList();
String[] titles = { "id", "用户名", "password", "sex","jurisdiction" };
String filename = "员工表";
/*打印信息
Iterator iterator=date.iterator();
while (iterator.hasNext())
{
User user=(User)iterator.next();
System.out.println(user.getId()+" "+user.getUsername()+" "+user.getPassword());
}*/
ExcelPoi.exportObject(response, date, titles, filename);
} catch (Exception e) {
//log.error(e);
}
return "";
}
HTML:
PS:我使用了boostrap框架,可以把class去掉
JS:
var linkAll=window.location.href; //下载所有数据
linkAll+='/exportUserAllList';
//上面的作为全局变量,也可以自己写到方法里面作为局部变量
//下载
function downAll() {
window.location.replace(linkAll);
}
//上传数据 start
function uploadFile() {
var file = $("#upload").val();
file = file.substring(file.lastIndexOf('.'), file.length);
if (file == '') {
alert("上传文件不能为空!");
} else if (file != '.xlsx' && file != '.xls') {
alert("请选择正确的excel类型文件!");
} else {
ajaxFileUpload();
}
}
function ajaxFileUpload() {
var formData = new FormData();
var name = $("#upload").val();
formData.append("file", $("#upload")[0].files[0]);
formData.append("name", name);
$.ajax({
url : "importCustomerList",
type : "post",
async : false,
data : formData,
processData : false,
contentType : false,
beforeSend : function() {
console.log("正在进行,请稍候");
},
success : function(e) {
if (e == "02") {
alert("导入失败");
} else {
alert(e);
}
}
});
}
PS:下载我使用的是 window.location.replace(linkAll);在controller里面我使用的是 @RequestMapping(value = “/User.html/exportUserAllList”, produces = “text/html;charset=UTF-8;”)。
本文主要是参考:https://blog.csdn.net/qq_38991369/article/details/94570143
同时很感谢该博主的帮助。
PS:可以在哔哩哔哩看这个例子跑起来的样子:https://www.bilibili.com/video/av88145412