import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
public String exportRecord(Record record) throws Exception {
List list = selList(record);
if (list.size() == 0 && StringUtils.isNotEmpty(record.getPersonName())) {
record.setPersonCode(record.getPersonName());
record.setPersonName("");
list = selList(record);
}
if (list != null) {
if (list.size() > 0) {
ExportExcel exportExcel = new ExportExcel(null, "记录信息", RecordExcel.class);
exportExcel.setDataList(list);
FileOutputStream fo = null;
String excelFileName = "record-" + System.currentTimeMillis(); + "-" + (new Date().getTime()) + ".xlsx";
String excelFilePath = "/file_server/excel" + "/" + excelFileName;
try {
File file = new File("/file_server/excel");
if (!file.exists()) {
file.mkdirs();
}
fo = new FileOutputStream("D:/data" + excelFilePath);
exportExcel.write(fo);
return "http://127.0.0.1:8080" + excelFilePath;
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(fo);
}
}
}
return null;
}
/**
* 记录表格模板
*/
public class RecordExcel {
@ExcelField(title = "姓名")
private String personName;
@ExcelField(title = "编号")
private String personCode;
@ExcelField(title = "部门")
private String deptName;
@ExcelField(title = "时间")
private String snapTime;
public void setPersonName(String personName) {
this.personName = personName;
}
public void setPersonCode(String personCode) {
this.personCode = personCode;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public void setSnapTime(String snapTime) {
this.snapTime = snapTime;
}
public String getPersonName() {
return personName;
}
public String getPersonCode() {
return personCode;
}
public String getDeptName() {
return deptName;
}
public String getSnapTime() {
return snapTime;
}
}
以下属于工具类(可直接复制):
import com.google.common.collect.Lists;
import com.core.common.utils.Reflections;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
*/
public class ExportExcel {
/**
* 单页最大的行数
*/
private static final int MAX_ROW_NUM = 11000;
/**
* 工作薄对象
*/
private SXSSFWorkbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map styles;
/**
* 当前行号
*/
private int rownum;
/**
* 注解列表(Object[]{ ExcelField, Field/Method })
*/
private List
import org.apache.poi.common.usermodel.HyperlinkType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 实体类字段映射excel
*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
/**
* 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
*/
String value() default "";
/**
* 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
*/
String title();
/**
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
*/
int type() default 0;
/**
* 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
*/
int align() default 0;
/**
* 导出字段字段排序(升序)
*/
int sort() default 0;
/**
* 链形式展现,0表示不采用链接 {@link org.apache.poi.common.usermodel.HyperlinkType}
*/
HyperlinkType link() default HyperlinkType.NONE;
/**
* 字体颜色 IndexedColors IndexedColors.GREY_50_PERCENT.getIndex() 23 默认颜色,未实现
*/
short color() default 23;
/**
* 如果是字典类型,请设置字典的type值
*/
String dictType() default "";
/**
* 反射类型
*/
Class> fieldType() default Class.class;
/**
* 字段归属组(根据分组导出导入)
*/
int[] groups() default {};
}
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 反射工具类
*/
public class Reflections {
private static final String GETTER_PREFIX = "get";
/**
* 调用Getter方法. 支持多级,如:对象名.对象名.方法
*/
public static Object invokeGetter(Object obj, String propertyName) {
Object object = obj;
for (String name : StringUtils.split(propertyName, ".")) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
}
return object;
}
/**
* 直接调用对象方法, 无视private/protected修饰符. 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. 同时匹配方法名+参数类型,
*/
public static Object invokeMethod(final Object obj, final String methodName, final Class>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
// throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
if (!"getSerialVersionUID".equals(methodName)) {
System.out.println("在类[{}]中找不到method[{}]方法");
}
return obj;
}
try {
return method.invoke(obj, args);
} catch (Exception e) {
throw convertReflectionExceptionToUnchecked(e);
}
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. 如向上转型到Object仍无法找到, 返回null. 匹配函数名+参数类型。
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod(final Object obj, final String methodName,
final Class>... parameterTypes) {
Validate.notNull(obj, "object can't be null");
Validate.notBlank(methodName, "methodName can't be blank");
for (Class> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
try {
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
} catch (NoSuchMethodException e) {
// Method不在当前类定义,继续向上转型
continue; // new add
}
}
return null;
}
/**
* 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
*/
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException(e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(((InvocationTargetException) e).getTargetException());
} else if (e instanceof RuntimeException) {
return (RuntimeException) e;
}
return new RuntimeException("Unexpected Checked Exception.", e);
}
}