excle导出、导⼊、下载_jeesite注解@ExcelField
介绍:对Apache POI 3.9的简单封装,实现Excel的导出导⼊功能。使⽤Annotation定义导出导⼊字段。
优点:1.简单易⽤,⽀持⼤数量导出,配置简单,代码量少。
2.⽀持Excel 2003、2007、2010(xls、xlsx)格式。
3.⽀持简单格式设置,对齐⽅式,排序等
4.可导出字典类型数据,⾃定义数据字段类型(例如:部门关联对象,部门名称与部门编号互转)。
5.⽆需建⽴导⼊模板,系统⾃动⽣成。
缺点:1.格式单⼀,⽆法导出格式⽐较复杂的表格。
2.不能使⽤模板进⾏导⼊,导出。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apachemons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId&le.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
⼀.实例
1.导出实例
/**
*
* @author yuzj
* @date 2017年3⽉3⽇下午2:59:05
* @description 数据导出
* @param childBaseinfo
* @param request
* @param response
* @param redirectAttributes
* @return
* @throws ParseException
*
*/
@RequestMapping(value = "export", method = RequestMethod.POST)
public String exportFile(ChildBaseinfo childBaseinfo,
HttpServletRequest request, HttpServletResponse response,
RedirectAttributes redirectAttributes,
@RequestParam String beginTime, @RequestParam String endTime,
@RequestParam String birthbeginTime,
@RequestParam String birthendTime) throws ParseException {
// 判断出⽣⽇期的格式
if (StringUtils.isNoneBlank(birthbeginTime)) {
Date birthbegin = vert(birthbeginTime);
Date birthend = vert(birthendTime);
if (birthbegin == null || birthend == null) {
addMessage(redirectAttributes, "你输⼊的出⽣⽇期格式不正确");
return "redirect:" + AdminPath() + "/child_baseinfo/documentStatistics/?repage";
}
Date birthd[] = childVaccinaterecordService.date(birthbegin,birthend);
if (birthd != null) {
childBaseinfo.setBirthbeginTime(birthd[0]);
childBaseinfo.setBirthendTime(birthd[1]);
} else {
addMessage(redirectAttributes, "你输⼊的出⽣⽇期起时间晚于⽌时间");
return "redirect:" + AdminPath() + "/child_baseinfo/documentStatistics/?repage";
}
}
// 起⽌时间
if (StringUtils.isNoneBlank(beginTime)) {
Date begin = vert(beginTime);
Date end = vert(endTime);
Date d[] = childVaccinaterecordService.date(begin, end);
if (d != null) {
childBaseinfo.setBeginTime(d[0]);
childBaseinfo.setEndTime(d[1]);
}
}
if (StringUtils.Officeinfo()) && "1".Officeinfo())) { childBaseinfo.FirstOffice() .getCode());
} else {
childBaseinfo.setOfficeinfo("");
}
Page<ChildBaseinfo> page = new Page<ChildBaseinfo>();
// 根据名字和时间排序
page.setOrderBy("A.createdate ASC");
page = childBaseinfoService.findPage(page, childBaseinfo);
childBaseinfo.setPage(page);
List<ChildBaseinfo> list = childBaseinfoService.findList_exp(childBaseinfo);
if (list.size() > 0) {
for (ChildBaseinfo childBaseinfo2 : list) {
// 转换地址信息
childBaseinfo2 = childBaseinfoService.updateAddr(childBaseinfo2);
}
}
try {
String fileName = "档案数据" + Date("yyyyMMddHHmmss")+ ".xlsx";
new ExportExcel("档案数据", ChildBaseinfo.class).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addMessage(redirectAttributes, "导出档案失败!失败信息:" + e.getMessage());
}
return "redirect:" + AdminPath()+ "/child_baseinfo/childBaseinfo/?repage";
}
2.导⼊实例
public String importFile(MultipartFile file) {
try {
int successNum = 0;
int failureNum = 0;
StringBuilder failureMsg = new StringBuilder();
// 创建导⼊Excel对象
ImportExcel ei = new ImportExcel(file, 1, 0);
// 获取传⼊Excel⽂件的数据,根据传⼊参数类型,⾃动转换为对象
List<User> list = ei.getDataList(User.class);
// 遍历数据,保存数据
for (User user : list){
try{
if ("true".equals(checkLoginName("", LoginName()))){
user.ptPassword("123456"));
BeanValidators.validateWithException(validator, user);
systemService.saveUser(user);
successNum++;
}else{
failureMsg.append("<br/>登录名 "+LoginName()+" 已存在; ");
failureNum++;
}
}catch(ConstraintViolationException ex){
failureMsg.append("<br/>登录名 "+LoginName()+" 导⼊失败:");
List<String> messageList = actPropertyAndMessageAsList(ex, ": ");
for (String message : messageList){
failureMsg.append(message+"; ");
failureNum++;
}
}catch (Exception ex) {
failureMsg.append("<br/>登录名 "+LoginName()+" 导⼊失败:"+ex.getMessage());
}
}
if (failureNum>0){
failureMsg.insert(0, ",失败 "+failureNum+" 条⽤户,导⼊信息如下:");
}
addFlashMessage("已成功导⼊ "+successNum+" 条⽤户"+failureMsg);
} catch (Exception e) {
addFlashMessage("导⼊⽤户失败!失败信息:"+e.getMessage());
}
return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";
}
3.模板下载
public String importFileTemplate() {
try {
String fileName = "⽤户数据导⼊模板.xlsx";
List<User> list = wArrayList(); list.User(true));
// 第三个参数设置为“2”表⽰输出为导⼊模板(1:导出数据;2:导⼊模板)
new ExportExcel("⽤户数据", User.class, 2).setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
addFlashMessage("导出⽤户失败!失败信息:"+e.getMessage());
}
return "redirect:"+BaseController.ADMIN_PATH+"/sys/user/?repage";
}
⼆、.⼯具类ExportExcel.java
/**
* Copyright © 2012-2014 <a href="github/thinkgem/jeesite">JeeSite</a> All rights reserved. */
package com.thinkgem.l;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import flect.Field;
import flect.Method;
SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apachemons.lang3.StringUtils;
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.Font;
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.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
llect.Lists;
import com.thinkgem.jeesitemon.utils.DateUtils;
import com.thinkgem.jeesitemon.utils.Encodes;
import com.thinkgem.jeesitemon.utils.Reflections;
import com.thinkgem.l.annotation.ExcelField;
import com.dules.sys.utils.DictUtils;
/**
* 导出Excel⽂件(导出“XLSX”格式,⽀持⼤数据量导出@see org.apache.poi.ss.SpreadsheetVersion)
* @author ThinkGem
* @version 2013-04-21
*/
public class ExportExcel {
private static Logger log = Logger(ExportExcel.class);
/**
* ⼯作薄对象
*/
private SXSSFWorkbook wb;
/**
* ⼯作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map<String, CellStyle> styles;
/**
* 当前⾏号
*/
private int rownum;
/**
* 注解列表(Object[]{ ExcelField, Field/Method })
*/
List<Object[]> annotationList = wArrayList();
/**
* @author QianHW
* @param sheetName
* @return根据sheet名称获取sheet
*/
public Sheet getSheet(String sheetName){
Sheet sheet = wb.getSheet(sheetName);
return sheet;
}
/**
* 构造函数
* @param title 表格标题,传“空值”,表⽰⽆标题
* @param cls 实体对象,通过annotation.ExportField获取标题
*/
public ExportExcel(String title, Class<?> cls){
this("", title, cls, 1,0);
}
public ExportExcel(String title, Class<?> cls, int type){
this("",title,cls,type,0);
}
public ExportExcel(String[] sheetnames,String[] titles, List<Class<?>> cls){
this("",titles[0],(0),1,0);
}
/**
* 构造函数导出单个sheet,带筛选条件
* @author QianHW
* @date 2018年7⽉19⽇下午7:03:48
* @param title
* @param cls 实体对象,通过annotation.ExportField获取标题
* @param conMap 筛选条件
*/
public ExportExcel(String title, Class<?> cls,Map<String, Object> conMap){
this("",title,cls,conMap,1);
}
// /**
// * @author QianHW
// * @date 2018年10⽉18⽇
/
/ * @param title
// * @param cls
// * @param conMap
// * @param dataList
// */
// public ExportExcel(String title,Class<?> cls,Map<String, Object> conMap,Map<String, List<?>> dataList){
//
// }
/**
* 构造函数
* @param title 表格标题,传“空值”,表⽰⽆标题
* @param cls 实体对象,通过annotation.ExportField获取标题
*/
public ExportExcel(String sheetname, String title, Class<?> cls){
this(sheetname, title, cls, 1,0);
}
/**
* 构造函数导出单个sheet,带筛选条件
* @author QianHW
* @date 2018年7⽉19⽇下午7:03:48
* @param title 表格标题,传“空值”,表⽰⽆标题
* @param cls 实体对象,通过annotation.ExportField获取标题
* @param conMap 筛选条件
* @param type 导出类型(1:导出数据;2:导出模板)
* @param groups 导⼊分组
*/
public ExportExcel(String sheetname, String title, Class<?> cls,Map<String, Object> conMap, int type, groups){ // Get annotation field
Field[] fs = DeclaredFields();
for (Field f : fs){
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, f});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, f});
}
}
}
// Get annotation method
Method[] ms = DeclaredMethods();
for (Method m : ms){
ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
if (g == efg){
inGroup = true;
annotationList.add(new Object[]{ef, m});
break;
}
}
}
}else{
annotationList.add(new Object[]{ef, m});
}
}
}
// Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort())pareTo(
new Integer(((ExcelField)o2[0]).sort()));
};
});
// Initialize
List<String> headerList = wArrayList();
for (Object[] os : annotationList){
String t = ((ExcelField)os[0]).title();
// 如果是导出,则去掉注释
if (type==1){
String[] ss = StringUtils.split(t, "**", 2);
if (ss.length==2){
t = ss[0];
}
}
headerList.add(t);
下载apache}
initialize(sheetname, title, headerList,conMap);
}
/**
* 构造函数导出单个sheet
* @param title 表格标题,传“空值”,表⽰⽆标题
* @param cls 实体对象,通过annotation.ExportField获取标题
* @param type 导出类型(1:导出数据;2:导出模板)
* @param groups 导⼊分组
* @param sht 第⼏个⼯作 sheet
*/
public ExportExcel(String sheetname, String title, Class<?> cls, int type,int sht, groups){ // Get annotation field
Field[] fs = DeclaredFields();
for (Field f : fs){
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){
if (groups!=null && groups.length>0){
boolean inGroup = false;
for (int g : groups){
if (inGroup){
break;
}
for (int efg : ef.groups()){
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论