diff --git a/.project b/.project new file mode 100644 index 0000000..2a6c952 --- /dev/null +++ b/.project @@ -0,0 +1,17 @@ + + + easypoi + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..14b697b --- /dev/null +++ b/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/deploy.bat b/deploy.bat new file mode 100644 index 0000000..92a7c3f --- /dev/null +++ b/deploy.bat @@ -0,0 +1 @@ +cmd /k mvn clean deploy -DskipTest \ No newline at end of file diff --git a/easypoi-base/.classpath b/easypoi-base/.classpath new file mode 100644 index 0000000..2aabaef --- /dev/null +++ b/easypoi-base/.classpath @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/easypoi-base/.project b/easypoi-base/.project new file mode 100644 index 0000000..354e3e6 --- /dev/null +++ b/easypoi-base/.project @@ -0,0 +1,23 @@ + + + easypoi-base + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/easypoi-base/.settings/org.eclipse.core.resources.prefs b/easypoi-base/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..1f887b6 --- /dev/null +++ b/easypoi-base/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 diff --git a/easypoi-base/.settings/org.eclipse.jdt.core.prefs b/easypoi-base/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..14f521d --- /dev/null +++ b/easypoi-base/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/easypoi-base/.settings/org.eclipse.m2e.core.prefs b/easypoi-base/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..14b697b --- /dev/null +++ b/easypoi-base/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/easypoi-base/pom.xml b/easypoi-base/pom.xml new file mode 100644 index 0000000..3fb8ca9 --- /dev/null +++ b/easypoi-base/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-base + + + + org.apache.poi + poi + + + org.apache.poi + poi-ooxml + + + org.apache.poi + poi-ooxml-schemas + + + org.apache.poi + poi-scratchpad + + + + + com.google.guava + guava + + + + commons-lang + commons-lang + + + + + + org.slf4j + slf4j-api + + + \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/ExcelCache.java b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/ExcelCache.java new file mode 100644 index 0000000..81d5cee --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/ExcelCache.java @@ -0,0 +1,46 @@ +package org.jeecgframework.poi.cache; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.poi.openxml4j.exceptions.InvalidFormatException; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.jeecgframework.poi.cache.manager.POICacheManager; + +/** + * Excel类型的缓存 + * + * @author JueYue + * @date 2014年2月11日 + * @version 1.0 + */ +public final class ExcelCache { + + public static Workbook getWorkbook(String url, int index) { + InputStream is = null; + try { + is = POICacheManager.getFile(url); + Workbook wb = WorkbookFactory.create(is); + // 删除其他的sheet + for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) { + if (i != index) { + wb.removeSheetAt(i); + } + } + return wb; + } catch (InvalidFormatException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + }finally{ + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/FileLoade.java b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/FileLoade.java new file mode 100644 index 0000000..8d6c660 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/FileLoade.java @@ -0,0 +1,52 @@ +package org.jeecgframework.poi.cache.manager; + +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 文件加载类,根据路径加载指定文件 + * @author JueYue + * @date 2014年2月10日 + * @version 1.0 + */ +class FileLoade { + + private static final Logger logger = LoggerFactory.getLogger(FileLoade.class); + + public byte[] getFile(String url){ + FileInputStream fileis = null; + ByteArrayOutputStream baos = null; + try { + String path = ExcelPublicUtil.getWebRootPath(url); + fileis = new FileInputStream(path); + baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len; + while ((len = fileis.read(buffer)) > -1) { + baos.write(buffer, 0, len); + } + baos.flush(); + return baos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + }finally{ + try { + if(fileis!=null)fileis.close(); + if(fileis!=null)baos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + logger.error(fileis +"这个路径文件没有找到,请查询"); + return null; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/POICacheManager.java b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/POICacheManager.java new file mode 100644 index 0000000..1a3d7fd --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/manager/POICacheManager.java @@ -0,0 +1,45 @@ +package org.jeecgframework.poi.cache.manager; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Arrays; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + +/** + * 缓存管理 + * + * @author JueYue + * @date 2014年2月10日 + * @version 1.0 + */ +public final class POICacheManager { + + private static LoadingCache loadingCache; + + static { + loadingCache = CacheBuilder.newBuilder() + .expireAfterWrite(1, TimeUnit.DAYS).maximumSize(50) + .build(new CacheLoader() { + @Override + public byte[] load(String url) throws Exception { + return new FileLoade().getFile(url); + } + }); + } + public static InputStream getFile(String id) { + try { + //复杂数据,防止操作原数据 + byte[] result = Arrays.copyOf(loadingCache.get(id), loadingCache.get(id).length); + return new ByteArrayInputStream(result); + } catch (ExecutionException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/package-info.java b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/package-info.java new file mode 100644 index 0000000..5d6d9c9 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/package-info.java @@ -0,0 +1,11 @@ +/** + * 对POI用到的模板进行缓存,进行统一管理,缓存工具暂时使用guava(脱离配置文件) + * 缓存方式统一为byte[] 屏蔽文件类型的差异 + * 缓存获取方式,URL或者URL+index(EXcel的) + */ +/** + * @author JueYue + * @date 2014年2月10日 + * @version 1.0 + */ +package org.jeecgframework.poi.cache; \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java new file mode 100644 index 0000000..aadd3ea --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java @@ -0,0 +1,93 @@ +package org.jeecgframework.poi.excel; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.*; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.TemplateExportParams; +import org.jeecgframework.poi.excel.export.ExcelExportServer; +import org.jeecgframework.poi.excel.export.template.ExcelExportOfTemplateUtil; + +/** + * excel 导出工具类 + * + * @author jueyue + * @version 1.0 + * @date 2013-10-17 + */ +public final class ExcelExportUtil { + + /** + * 一个excel 创建多个sheet + * + * @param list + * 多个Map key title 对应表格Title key entity 对应表格对应实体 key data + * Collection 数据 + * @return + */ + public static HSSFWorkbook exportExcel(List> list) { + HSSFWorkbook workbook = new HSSFWorkbook(); + ExcelExportServer server = new ExcelExportServer(); + for (Map map : list) { + server.createSheet(workbook, + (ExportParams) map.get("title"), + (Class) map.get("entity"), + (Collection) map.get("data")); + } + return workbook; + } + + /** + * @param entity + * 表格标题属性 + * @param pojoClass + * Excel对象Class + * @param dataSet + * Excel对象数据List + */ + public static HSSFWorkbook exportExcel(ExportParams entity, + Class pojoClass, Collection dataSet) { + HSSFWorkbook workbook = new HSSFWorkbook(); + new ExcelExportServer().createSheet(workbook, entity, pojoClass, dataSet); + return workbook; + } + + /** + * 导出文件通过模板解析 + * + * @param params + * 导出参数类 + * @param pojoClass + * 对应实体 + * @param dataSet + * 实体集合 + * @param map + * 模板集合 + * @return + */ + public static Workbook exportExcel(TemplateExportParams params, + Class pojoClass, Collection dataSet, Map map) { + return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, + pojoClass, dataSet, map); + } + + /** + * 导出文件通过模板解析只有模板,没有集合 + * + * @param params + * 导出参数类 + * @param map + * 模板集合 + * @return + */ + public static Workbook exportExcel(TemplateExportParams params, + Map map) { + return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, + null, null, map); + } + + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtil.java new file mode 100644 index 0000000..ce57016 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtil.java @@ -0,0 +1,112 @@ +package org.jeecgframework.poi.excel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import org.apache.poi.ss.formula.functions.T; +import org.jeecgframework.poi.excel.entity.ImportParams; +import org.jeecgframework.poi.excel.entity.result.ExcelImportResult; +import org.jeecgframework.poi.excel.imports.ExcelImportServer; + +/** + * Excel 导入工具 + * + * @author JueYue + * @date 2013-9-24 + * @version 1.0 + */ +@SuppressWarnings({ "hiding", "unchecked" }) +public class ExcelImportUtil { + + /** + * Excel 导入 数据源本地文件,返回校验结果 字段类型 Integer,Long,Double,Date,String,Boolean + * + * @param file + * @param pojoClass + * @param params + * @return + * @throws Exception + */ + public static ExcelImportResult importExcelVerify(File file, + Class pojoClass, ImportParams params) { + FileInputStream in = null; + try { + in = new FileInputStream(file); + return new ExcelImportServer().importExcelByIs(in, pojoClass, + params); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * Excel 导入 数据源本地文件,不返回校验结果 导入 字 段类型 Integer,Long,Double,Date,String,Boolean + * + * @param file + * @param pojoClass + * @param params + * @return + * @throws Exception + */ + public static List importExcel(File file, Class pojoClass, + ImportParams params) { + FileInputStream in = null; + List result = null; + try { + in = new FileInputStream(file); + result = new ExcelImportServer().importExcelByIs(in, pojoClass, + params).getList(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return result; + } + + /** + * Excel 导入 数据源IO流,返回校验结果 字段类型 Integer,Long,Double,Date,String,Boolean + * + * @param file + * @param pojoClass + * @param params + * @return + * @throws Exception + */ + public static ExcelImportResult importExcelByIsAndVerify( + InputStream inputstream, Class pojoClass, ImportParams params) + throws Exception { + return new ExcelImportServer().importExcelByIs(inputstream, pojoClass, + params); + } + + /** + * Excel 导入 数据源IO流,不返回校验结果 导入 字段类型 Integer,Long,Double,Date,String,Boolean + * + * @param file + * @param pojoClass + * @param params + * @return + * @throws Exception + */ + public static List importExcelByIs(InputStream inputstream, + Class pojoClass, ImportParams params) throws Exception { + return new ExcelImportServer().importExcelByIs(inputstream, pojoClass, + params).getList(); + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/Excel.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/Excel.java new file mode 100644 index 0000000..94e9212 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/Excel.java @@ -0,0 +1,101 @@ +package org.jeecgframework.poi.excel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +/** + * Excel 导出基本注释 + * @author JueYue + * @date 2014年6月20日 下午10:25:12 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Excel { + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name(); + + /** + * 导出时在excel中每个列的宽 单位为字符,一个汉字=2个字符 如 以列名列内容中较合适的长度 例如姓名列6 【姓名一般三个字】 + * 性别列4【男女占1,但是列标题两个汉字】 限制1-255 + */ + public int width() default 10; + + /** + * 导出时在excel中每个列的高度 单位为字符,一个汉字=2个字符 + */ + public int height() default 10; + + /** + * 值得替换 导出是{a_id,b_id} 导入反过来,所以只用写一个 + */ + public String[] replace() default {}; + + /** + * 导出类型 1 是文本 2 是图片,3是函数 默认是文本 + */ + public int type() default 1; + + /** + * 导出类型 1 从file读取 2 是从数据库中读取 默认是文件 同样导入也是一样的 + */ + public int imageType() default 1; + + /** + * 导入路径,如果是图片可以填写,默认是upload/className/ IconEntity这个类对应的就是upload/Icon/ + * + */ + public String savePath() default "upload"; + + /** + * 展示到第几个可以使用a_id,b_id来确定不同排序 + */ + public String orderNum() default "0"; + + /** + * 是否换行 即支持\n + */ + public boolean isWrap() default true; + + /** + * 是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row) + */ + public boolean needMerge() default false; + /** + * 纵向合并内容相同的单元格 + */ + public boolean mergeVertical() default false; + + /** + * 合并单元格依赖关系,比如第二列合并是基于第一列 则{1}就可以了 + */ + public int[] mergeRely() default {}; + + /** + * 导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式 + */ + public String databaseFormat() default "yyyyMMddHHmmss"; + + /** + * 导出的时间格式,以这个是否为空来判断是否需要格式化日期 + */ + public String exportFormat() default ""; + + /** + * 导入的时间格式,以这个是否为空来判断是否需要格式化日期 + */ + public String importFormat() default ""; + + /** + * 时间格式,相当于同时设置了exportFormat 和 importFormat + */ + public String format() default ""; + + /** + * cell 写入的设置的函数 + */ + public String cellFormula() default ""; +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelCollection.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelCollection.java new file mode 100644 index 0000000..c76961c --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelCollection.java @@ -0,0 +1,39 @@ +package org.jeecgframework.poi.excel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.ArrayList; + +/** + * 导出的集合 + * + * @author jueyue 2013年8月24日 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ExcelCollection { + + /** + * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 + */ + public String id() default ""; + + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name(); + + /** + * 展示到第几个同样可以使用a_id,b_id + * + */ + public String orderNum() default "0"; + + /** + * 创建时创建的类型 默认值是 arrayList + */ + public Class type() default ArrayList.class; +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelEntity.java new file mode 100644 index 0000000..88b9ed7 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelEntity.java @@ -0,0 +1,28 @@ +package org.jeecgframework.poi.excel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 标记是不是导出excel 标记为实体类 + * + * @author jueyue + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ExcelEntity { + + /** + * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 + */ + public String id() default ""; + + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name() default ""; +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelIgnore.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelIgnore.java new file mode 100644 index 0000000..4e96047 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelIgnore.java @@ -0,0 +1,18 @@ +package org.jeecgframework.poi.excel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 标记为excel 创建实体忽略,放置死循环的造成 + * @author JueYue + * @date 2013-9-24 + * @version 1.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ExcelIgnore { + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelTarget.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelTarget.java new file mode 100644 index 0000000..43ad7e1 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelTarget.java @@ -0,0 +1,21 @@ +package org.jeecgframework.poi.excel.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * excel 导出是用于标记id的 + * + * @author jueyue + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface ExcelTarget { + /** + * 定义excel导出ID 来限定导出字段 + */ + public String value(); +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelVerify.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelVerify.java new file mode 100644 index 0000000..4c949ac --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/annotation/ExcelVerify.java @@ -0,0 +1,70 @@ +package org.jeecgframework.poi.excel.annotation; + +/** + * Excel 导入校验 + * + * @author JueYue + * @date 2014年6月23日 下午10:46:26 + */ +public @interface ExcelVerify { + /** + * 接口校验 + * @return + */ + public boolean interHandler() default true; + + /** + * 不允许空 + * + * @return + */ + public boolean notNull() default false; + + /** + * 是13位移动电话 + * + * @return + */ + public boolean isMobile() default false; + /** + * 是座机号码 + * + * @return + */ + public boolean isTel() default false; + + /** + * 是电子邮件 + * + * @return + */ + public boolean isEmail() default false; + + /** + * 最小长度 + * + * @return + */ + public int minLength() default -1; + + /** + * 最大长度 + * + * @return + */ + public int maxLength() default -1; + + /** + * 正在表达式 + * + * @return + */ + public String regex() default ""; + /** + * 正在表达式,错误提示信息 + * + * @return + */ + public String regexTip() default "数据不符合规范"; + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExcelBaseParams.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExcelBaseParams.java new file mode 100644 index 0000000..bc19f2f --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExcelBaseParams.java @@ -0,0 +1,25 @@ +package org.jeecgframework.poi.excel.entity; + +import org.jeecgframework.poi.handler.inter.IExcelDataHandler; + +/** + * 基础参数 + * @author JueYue + * @date 2014年6月20日 下午1:56:52 + */ +public class ExcelBaseParams { + /** + * 数据处理接口,以此为主,replace,format都在这后面 + */ + private IExcelDataHandler dataHanlder; + + public IExcelDataHandler getDataHanlder() { + return dataHanlder; + } + + public void setDataHanlder(IExcelDataHandler dataHanlder) { + this.dataHanlder = dataHanlder; + } + + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExportParams.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExportParams.java new file mode 100644 index 0000000..dbd9132 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ExportParams.java @@ -0,0 +1,125 @@ +package org.jeecgframework.poi.excel.entity; + +import org.apache.poi.hssf.util.HSSFColor; + +/** + * Excel 导出参数 + * + * @author jueyue + * @version 1.0 2013年8月24日 + */ +public class ExportParams extends ExcelBaseParams { + + public ExportParams() { + + } + + public ExportParams(String title, String sheetName) { + this.title = title; + this.sheetName = sheetName; + } + + public ExportParams(String title, String secondTitle, String sheetName) { + this.title = title; + this.secondTitle = secondTitle; + this.sheetName = sheetName; + } + + /** + * 表格名称 + */ + private String title; + /** + * 表格名称 + */ + private short titleHeight = 20; + /** + * 第二行名称 + */ + private String secondTitle; + /** + * 表格名称 + */ + private short secondTitleHeight = 8; + /** + * sheetName + */ + private String sheetName; + /** + * 过滤的属性 + */ + private String[] exclusions; + /** + * 表头颜色 + */ + private short color = HSSFColor.WHITE.index; + + /** + * 属性说明行的颜色 例如:HSSFColor.SKY_BLUE.index 默认 + */ + private short headerColor = HSSFColor.SKY_BLUE.index; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSheetName() { + return sheetName; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public short getColor() { + return color; + } + + public void setColor(short color) { + this.color = color; + } + + public String[] getExclusions() { + return exclusions; + } + + public void setExclusions(String[] exclusions) { + this.exclusions = exclusions; + } + + public String getSecondTitle() { + return secondTitle; + } + + public void setSecondTitle(String secondTitle) { + this.secondTitle = secondTitle; + } + + public short getHeaderColor() { + return headerColor; + } + + public void setHeaderColor(short headerColor) { + this.headerColor = headerColor; + } + + public short getTitleHeight() { + return (short) (titleHeight * 50); + } + + public void setTitleHeight(short titleHeight) { + this.titleHeight = titleHeight; + } + + public short getSecondTitleHeight() { + return (short) (secondTitleHeight * 50); + } + + public void setSecondTitleHeight(short secondTitleHeight) { + this.secondTitleHeight = secondTitleHeight; + } +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ImportParams.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ImportParams.java new file mode 100644 index 0000000..1644e50 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/ImportParams.java @@ -0,0 +1,111 @@ +package org.jeecgframework.poi.excel.entity; + +import org.jeecgframework.poi.handler.inter.IExcelVerifyHandler; + +/** + * 导入参数设置 + * + * @author JueYue + * @date 2013-9-24 + * @version 1.0 + */ +public class ImportParams extends ExcelBaseParams { + /** + * 表格标题行数,默认0 + */ + private int titleRows = 0; + /** + * 表头行数,默认1 + */ + private int headRows = 1; + /** + * 字段真正值和列标题之间的距离 默认0 + */ + private int startRows = 0; + /** + * 主键设置,如何这个cell没有值,就跳过 或者认为这个是list的下面的值 + */ + private int keyIndex = 0; + /** + * 上传表格需要读取的sheet 数量,默认为1 + */ + private int sheetNum = 1; + /** + * 是否需要保存上传的Excel,默认为false + */ + private boolean needSave = false; + /** + * 保存上传的Excel目录,默认是 如 TestEntity这个类保存路径就是 + * upload/excelUpload/Test/yyyyMMddHHmss_***** 保存名称上传时间_五位随机数 + */ + private String saveUrl = "upload/excelUpload"; + /** + * 校验处理接口 + */ + private IExcelVerifyHandler verifyHanlder; + + public int getTitleRows() { + return titleRows; + } + + public void setTitleRows(int titleRows) { + this.titleRows = titleRows; + } + + public int getStartRows() { + return startRows; + } + + public void setStartRows(int startRows) { + this.startRows = startRows; + } + + public int getSheetNum() { + return sheetNum; + } + + public void setSheetNum(int sheetNum) { + this.sheetNum = sheetNum; + } + + public int getKeyIndex() { + return keyIndex; + } + + public void setKeyIndex(int keyIndex) { + this.keyIndex = keyIndex; + } + + public boolean isNeedSave() { + return needSave; + } + + public void setNeedSave(boolean needSave) { + this.needSave = needSave; + } + + public String getSaveUrl() { + return saveUrl; + } + + public void setSaveUrl(String saveUrl) { + this.saveUrl = saveUrl; + } + + public IExcelVerifyHandler getVerifyHanlder() { + return verifyHanlder; + } + + public void setVerifyHanlder(IExcelVerifyHandler verifyHanlder) { + this.verifyHanlder = verifyHanlder; + } + + public int getHeadRows() { + return headRows; + } + + public void setHeadRows(int headRows) { + this.headRows = headRows; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/TemplateExportParams.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/TemplateExportParams.java new file mode 100644 index 0000000..ba0c7b2 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/TemplateExportParams.java @@ -0,0 +1,101 @@ +package org.jeecgframework.poi.excel.entity; + +/** + * 模板导出参数设置 + * + * @author JueYue + * @date 2013-10-17 + * @version 1.0 + */ +public class TemplateExportParams extends ExcelBaseParams { + + public TemplateExportParams() { + + } + + public TemplateExportParams(String templateUrl) { + this.templateUrl = templateUrl; + } + + public TemplateExportParams(String templateUrl, + int sheetNum) { + this.templateUrl = templateUrl; + this.sheetNum = sheetNum; + } + + public TemplateExportParams(String templateUrl, + String sheetName) { + this.templateUrl = templateUrl; + this.sheetName = sheetName; + } + + public TemplateExportParams(String templateUrl, String sheetName, + int sheetNum) { + this.templateUrl = templateUrl; + this.sheetName = sheetName; + this.sheetNum = sheetNum; + } + + /** + * 模板的路径 + */ + private String templateUrl; + + /** + * 需要导出的第几个 sheetNum,默认是第0个 + */ + private int sheetNum = 0; + /** + * 这只sheetName 不填就使用原来的 + */ + private String sheetName; + /** + * 表格列标题行数,默认1 + */ + private int headingRows = 1; + /** + * 表格列标题开始行,默认1 + */ + private int headingStartRow = 2; + + public String getTemplateUrl() { + return templateUrl; + } + + public void setTemplateUrl(String templateUrl) { + this.templateUrl = templateUrl; + } + + public int getSheetNum() { + return sheetNum; + } + + public void setSheetNum(int sheetNum) { + this.sheetNum = sheetNum; + } + + public String getSheetName() { + return sheetName; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public int getHeadingRows() { + return headingRows; + } + + public void setHeadingRows(int headingRows) { + this.headingRows = headingRows; + } + + public int getHeadingStartRow() { + return headingStartRow; + } + + public void setHeadingStartRow(int headingStartRow) { + this.headingStartRow = headingStartRow; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ComparatorExcelField.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ComparatorExcelField.java new file mode 100644 index 0000000..5a3e2ed --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ComparatorExcelField.java @@ -0,0 +1,17 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.util.Comparator; + +/** + * 按照升序排序 + * @author jueyue + * + */ +public class ComparatorExcelField implements Comparator { + + + public int compare(ExcelExportEntity prev,ExcelExportEntity next) { + return prev.getOrderNum() - next.getOrderNum(); + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelBaseEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelBaseEntity.java new file mode 100644 index 0000000..a998936 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelBaseEntity.java @@ -0,0 +1,94 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.lang.reflect.Method; +import java.util.List; +/** + * Excel 导入导出基础对象类 + * @author JueYue + * @date 2014年6月20日 下午2:26:09 + */ +public class ExcelBaseEntity { + /** + * 对应name + */ + private String name; + /** + * 对应type + */ + private int type; + /** + * 数据库格式 + */ + private String databaseFormat; + /** + * 导出日期格式 + */ + private String format; + /** + * 导出日期格式 + */ + private String[] replace; + /** + * set/get方法 + */ + private Method method; + + private List methods; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public String getDatabaseFormat() { + return databaseFormat; + } + + public void setDatabaseFormat(String databaseFormat) { + this.databaseFormat = databaseFormat; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public String[] getReplace() { + return replace; + } + + public void setReplace(String[] replace) { + this.replace = replace; + } + + public Method getMethod() { + return method; + } + + public void setMethod(Method method) { + this.method = method; + } + + public List getMethods() { + return methods; + } + + public void setMethods(List methods) { + this.methods = methods; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelCollectionParams.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelCollectionParams.java new file mode 100644 index 0000000..2c76411 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelCollectionParams.java @@ -0,0 +1,52 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.util.Map; + + +/** + * Excel 对于的 Collection + * + * @author JueYue + * @date 2013-9-26 + * @version 1.0 + */ +public class ExcelCollectionParams { + + /** + * 集合对应的名称 + */ + private String name; + /** + * 实体对象 + */ + private Class type; + /** + * 这个list下面的参数集合实体对象 + */ + private Map excelParams; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + public Map getExcelParams() { + return excelParams; + } + + public void setExcelParams(Map excelParams) { + this.excelParams = excelParams; + } +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelExportEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelExportEntity.java new file mode 100644 index 0000000..fec230c --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelExportEntity.java @@ -0,0 +1,126 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.util.List; + +/** + * excel 导出工具类,对cell类型做映射 + * + * @author jueyue + * @version 1.0 2013年8月24日 + */ +public class ExcelExportEntity extends ExcelBaseEntity { + + private int width; + private int height; + /** + * 图片的类型,1是文件,2是数据库 + */ + private int exportImageType; + /** + * 排序顺序 + */ + private int orderNum; + /** + * 是否支持换行 + */ + private boolean isWrap; + /** + * 是否需要合并 + */ + private boolean needMerge; + /** + * 单元格纵向合并 + */ + private boolean mergeVertical; + /** + * 合并依赖 + */ + private int[] mergeRely; + /** + * cell 函数 + */ + private String cellFormula; + + private List list; + + public int getWidth() { + return width; + } + + public void setWidth(int width) { + this.width = width; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public int getHeight() { + return height; + } + + public void setHeight(int height) { + this.height = height; + } + + public int getOrderNum() { + return orderNum; + } + + public void setOrderNum(int orderNum) { + this.orderNum = orderNum; + } + + public boolean isWrap() { + return isWrap; + } + + public void setWrap(boolean isWrap) { + this.isWrap = isWrap; + } + + public boolean isNeedMerge() { + return needMerge; + } + + public void setNeedMerge(boolean needMerge) { + this.needMerge = needMerge; + } + + public int[] getMergeRely() { + return mergeRely; + } + + public void setMergeRely(int[] mergeRely) { + this.mergeRely = mergeRely; + } + + public int getExportImageType() { + return exportImageType; + } + + public void setExportImageType(int exportImageType) { + this.exportImageType = exportImageType; + } + + public String getCellFormula() { + return cellFormula; + } + + public void setCellFormula(String cellFormula) { + this.cellFormula = cellFormula; + } + + public boolean isMergeVertical() { + return mergeVertical; + } + + public void setMergeVertical(boolean mergeVertical) { + this.mergeVertical = mergeVertical; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelImportEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelImportEntity.java new file mode 100644 index 0000000..451c44f --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelImportEntity.java @@ -0,0 +1,81 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.util.List; +/** + * excel 导入工具类,对cell类型做映射 + * @author jueyue + * @version 1.0 2013年8月24日 + */ +public class ExcelImportEntity extends ExcelBaseEntity { + /** + * 对应 Collection NAME + */ + private String collectionName; + /** + * 保存图片的地址 + */ + private String saveUrl; + /** + * 保存图片的类型,1是文件,2是数据库 + */ + private int saveType; + /** + * 对应exportType + */ + private String classType; + /** + * 校驗參數 + */ + private ExcelVerifyEntity verify; + + private List list; + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public String getSaveUrl() { + return saveUrl; + } + + public void setSaveUrl(String saveUrl) { + this.saveUrl = saveUrl; + } + + public String getClassType() { + return classType; + } + + public void setClassType(String classType) { + this.classType = classType; + } + + public String getCollectionName() { + return collectionName; + } + + public void setCollectionName(String collectionName) { + this.collectionName = collectionName; + } + + public int getSaveType() { + return saveType; + } + + public void setSaveType(int saveType) { + this.saveType = saveType; + } + + public ExcelVerifyEntity getVerify() { + return verify; + } + + public void setVerify(ExcelVerifyEntity verify) { + this.verify = verify; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelVerifyEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelVerifyEntity.java new file mode 100644 index 0000000..ac931da --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/ExcelVerifyEntity.java @@ -0,0 +1,127 @@ +package org.jeecgframework.poi.excel.entity.params; + +/** + * Excel 校验对象 + * + * @author JueYue + * @date 2014年6月29日 下午4:24:59 + */ +public class ExcelVerifyEntity { + + /** + * 接口校验 + * + * @return + */ + private boolean interHandler; + + /** + * 不允许空 + * + * @return + */ + private boolean notNull; + + /** + * 是13位移动电话 + * + * @return + */ + private boolean isMobile; + /** + * 是座机号码 + * + * @return + */ + private boolean isTel; + + /** + * 是电子邮件 + * + * @return + */ + private boolean isEmail; + + /** + * 最小长度 + * + * @return + */ + private int minLength; + + /** + * 最大长度 + * + * @return + */ + private int maxLength; + + /** + * 正在表达式 + * + * @return + */ + private String regex; + /** + * 正在表达式,错误提示信息 + * + * @return + */ + private String regexTip; + + public boolean isInterHandler() { + return interHandler; + } + public void setInterHandler(boolean interHandler) { + this.interHandler = interHandler; + } + public boolean isNotNull() { + return notNull; + } + public void setNotNull(boolean notNull) { + this.notNull = notNull; + } + public boolean isMobile() { + return isMobile; + } + public void setMobile(boolean isMobile) { + this.isMobile = isMobile; + } + public boolean isTel() { + return isTel; + } + public void setTel(boolean isTel) { + this.isTel = isTel; + } + public boolean isEmail() { + return isEmail; + } + public void setEmail(boolean isEmail) { + this.isEmail = isEmail; + } + public int getMinLength() { + return minLength; + } + public void setMinLength(int minLength) { + this.minLength = minLength; + } + public int getMaxLength() { + return maxLength; + } + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + public String getRegex() { + return regex; + } + public void setRegex(String regex) { + this.regex = regex; + } + public String getRegexTip() { + return regexTip; + } + public void setRegexTip(String regexTip) { + this.regexTip = regexTip; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/MergeEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/MergeEntity.java new file mode 100644 index 0000000..a7c1626 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/params/MergeEntity.java @@ -0,0 +1,69 @@ +package org.jeecgframework.poi.excel.entity.params; + +import java.util.List; + +/** + * 合并单元格使用对象 + * + * Created by jue on 14-6-11. + */ +public class MergeEntity { + /** + * 合并开始行 + */ + private int startRow; + /** + * 合并结束行 + */ + private int endRow; + /** + * 文字 + */ + private String text; + /** + * 依赖关系文本 + */ + private List relyList; + + public MergeEntity(){ + + } + + public MergeEntity(String text,int startRow,int endRow){ + this.text = text; + this.endRow = endRow; + this.startRow = startRow; + } + + public int getStartRow() { + return startRow; + } + + public void setStartRow(int startRow) { + this.startRow = startRow; + } + + public int getEndRow() { + return endRow; + } + + public void setEndRow(int endRow) { + this.endRow = endRow; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public List getRelyList() { + return relyList; + } + + public void setRelyList(List relyList) { + this.relyList = relyList; + } +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelImportResult.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelImportResult.java new file mode 100644 index 0000000..9b4a9c0 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelImportResult.java @@ -0,0 +1,63 @@ +package org.jeecgframework.poi.excel.entity.result; + +import java.util.List; + +import org.apache.poi.ss.usermodel.Workbook; + +/** + * 导入返回类 + * + * @author JueYue + * @date 2014年6月29日 下午5:12:10 + */ +@SuppressWarnings("rawtypes") +public class ExcelImportResult { + + public ExcelImportResult() { + + } + + public ExcelImportResult(List list, boolean verfiyFail, Workbook workbook) { + this.list = list; + this.verfiyFail = verfiyFail; + this.workbook = workbook; + } + + /** + * 结果集 + */ + private List list; + /** + * 是否存在校验失败 + */ + private boolean verfiyFail; + /** + * 数据源 + */ + private Workbook workbook; + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public boolean isVerfiyFail() { + return verfiyFail; + } + + public void setVerfiyFail(boolean verfiyFail) { + this.verfiyFail = verfiyFail; + } + + public Workbook getWorkbook() { + return workbook; + } + + public void setWorkbook(Workbook workbook) { + this.workbook = workbook; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelVerifyHanlderResult.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelVerifyHanlderResult.java new file mode 100644 index 0000000..d9f1bbb --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/result/ExcelVerifyHanlderResult.java @@ -0,0 +1,48 @@ +package org.jeecgframework.poi.excel.entity.result; + +/** + * Excel导入处理返回结果 + * + * @author JueYue + * @date 2014年6月23日 下午11:03:29 + */ +public class ExcelVerifyHanlderResult { + /** + * 是否正确 + */ + private boolean success; + /** + * 错误信息 + */ + private String msg; + + public ExcelVerifyHanlderResult() { + + } + + public ExcelVerifyHanlderResult(boolean success) { + this.success = success; + } + + public ExcelVerifyHanlderResult(boolean success, String msg) { + this.success = success; + this.msg = msg; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/vo/PoiBaseConstants.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/vo/PoiBaseConstants.java new file mode 100644 index 0000000..9469043 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/entity/vo/PoiBaseConstants.java @@ -0,0 +1,15 @@ +package org.jeecgframework.poi.excel.entity.vo; + +/** + * 基础常量 + * Created by jue on 14-4-21. + */ +public interface PoiBaseConstants { + + public static String GET = "get"; + + public static String SET = "set"; + + public static String IS = "is"; + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java new file mode 100644 index 0000000..628a929 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java @@ -0,0 +1,711 @@ +package org.jeecgframework.poi.excel.export; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.imageio.ImageIO; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFClientAnchor; +import org.apache.poi.hssf.usermodel.HSSFRichTextString; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.RichTextString; +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.jeecgframework.poi.excel.annotation.Excel; +import org.jeecgframework.poi.excel.annotation.ExcelCollection; +import org.jeecgframework.poi.excel.annotation.ExcelEntity; +import org.jeecgframework.poi.excel.entity.params.ComparatorExcelField; +import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; +import org.jeecgframework.poi.excel.entity.params.MergeEntity; +import org.jeecgframework.poi.handler.inter.IExcelDataHandler; +import org.jeecgframework.poi.util.ExcelPublicUtil; + +/** + * 导出基础服务 + * + * @author JueYue + * @date 2014年6月17日 下午6:15:13 + */ +public abstract class ExcelExportBase { + + protected IExcelDataHandler dataHanlder; + + protected List needHanlderList; + + /** + * 获取需要导出的全部字段 + * + * @param exclusions + * @param targetId + * 目标ID + * @param fields + * @throws Exception + */ + public void getAllExcelField(String[] exclusions, String targetId, + Field[] fields, List excelParams, + Class pojoClass, List getMethods) throws Exception { + List exclusionsList = exclusions != null ? Arrays + .asList(exclusions) : null; + ExcelExportEntity excelEntity; + // 遍历整个filed + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + // 先判断是不是collection,在判断是不是java自带对象,之后就是我们自己的对象了 + if (ExcelPublicUtil.isNotUserExcelUserThis(exclusionsList, field, + targetId)) { + continue; + } + if (ExcelPublicUtil.isCollection(field.getType())) { + ExcelCollection excel = field + .getAnnotation(ExcelCollection.class); + ParameterizedType pt = (ParameterizedType) field + .getGenericType(); + Class clz = (Class) pt.getActualTypeArguments()[0]; + List list = new ArrayList(); + getAllExcelField(exclusions, + StringUtils.isNotEmpty(excel.id()) ? excel.id() + : targetId, + ExcelPublicUtil.getClassFields(clz), list, clz, null); + excelEntity = new ExcelExportEntity(); + excelEntity.setName(getExcelName(excel.name(), targetId)); + excelEntity + .setOrderNum(getCellOrder(excel.orderNum(), targetId)); + excelEntity.setMethod(ExcelPublicUtil.getMethod( + field.getName(), pojoClass)); + excelEntity.setList(list); + excelParams.add(excelEntity); + } else if (ExcelPublicUtil.isJavaClass(field)) { + excelParams.add(createExcelExportEntity(field, targetId, + pojoClass, getMethods)); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + pojoClass)); + ExcelEntity excel = field.getAnnotation(ExcelEntity.class); + getAllExcelField(exclusions, + StringUtils.isNotEmpty(excel.id()) ? excel.id() + : targetId, + ExcelPublicUtil.getClassFields(field.getType()), + excelParams, field.getType(), newMethods); + } + } + } + + /** + * 创建导出实体对象 + * + * @param field + * @param targetId + * @param pojoClass + * @param getMethods + * @return + * @throws Exception + */ + private ExcelExportEntity createExcelExportEntity(Field field, + String targetId, Class pojoClass, List getMethods) + throws Exception { + Excel excel = field.getAnnotation(Excel.class); + ExcelExportEntity excelEntity = new ExcelExportEntity(); + excelEntity.setType(excel.type()); + getExcelField(targetId, field, excelEntity, excel, pojoClass); + if (getMethods != null) { + List newMethods = new ArrayList(); + newMethods.addAll(getMethods); + newMethods.add(excelEntity.getMethod()); + excelEntity.setMethods(newMethods); + } + return excelEntity; + } + + /** + * 判断在这个单元格显示的名称 + * + * @param exportName + * @param targetId + * @return + */ + public String getExcelName(String exportName, String targetId) { + if (exportName.indexOf(",") < 0) { + return exportName; + } + String[] arr = exportName.split(","); + for (String str : arr) { + if (str.indexOf(targetId) != -1) { + return str.split("_")[0]; + } + } + return null; + } + + /** + * 获取这个字段的顺序 + * + * @param orderNum + * @param targetId + * @return + */ + public int getCellOrder(String orderNum, String targetId) { + if (isInteger(orderNum) || targetId == null) { + return Integer.valueOf(orderNum); + } + String[] arr = orderNum.split(","); + String[] temp; + for (String str : arr) { + temp = str.split("_"); + if (targetId.equals(temp[1])) { + return Integer.valueOf(temp[0]); + } + } + return 0; + } + + /** + * 判断字符串是否是整数 + */ + public boolean isInteger(String value) { + try { + Integer.parseInt(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + /** + * 注解到导出对象的转换 + * + * @param targetId + * @param field + * @param excelEntity + * @param excel + * @param pojoClass + * @throws Exception + */ + private void getExcelField(String targetId, Field field, + ExcelExportEntity excelEntity, Excel excel, Class pojoClass) + throws Exception { + excelEntity.setName(getExcelName(excel.name(), targetId)); + excelEntity.setWidth(excel.width()); + excelEntity.setHeight(excel.height()); + excelEntity.setNeedMerge(excel.needMerge()); + excelEntity.setMergeVertical(excel.mergeVertical()); + excelEntity.setMergeRely(excel.mergeRely()); + excelEntity.setReplace(excel.replace()); + excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId)); + excelEntity.setWrap(excel.isWrap()); + excelEntity.setExportImageType(excel.imageType()); + excelEntity.setDatabaseFormat(excel.databaseFormat()); + excelEntity + .setFormat(StringUtils.isNotEmpty(excel.exportFormat()) ? excel + .exportFormat() : excel.format()); + String fieldname = field.getName(); + excelEntity.setMethod(ExcelPublicUtil.getMethod(fieldname, pojoClass)); + } + + /** + * 合并单元格 + * + * @param sheet + * @param excelParams + */ + public void mergeCells(Sheet sheet, List excelParams, + int titleHeight) { + Map mergeMap = getMergeDataMap(excelParams); + Map mergeDataMap = new HashMap(); + if (mergeMap.size() == 0) { + return; + } + Row row; + Set sets = mergeMap.keySet(); + String text; + for (int i = titleHeight; i <= sheet.getLastRowNum(); i++) { + row = sheet.getRow(i); + for (Integer index : sets) { + if (row.getCell(index) == null) { + mergeDataMap.get(index).setEndRow(i); + } else { + text = row.getCell(index).getStringCellValue(); + if (StringUtils.isNotEmpty(text)) { + hanlderMergeCells(index, i, text, mergeDataMap, sheet, + row.getCell(index), mergeMap.get(index)); + } else { + mergeCellOrContinue(index, mergeDataMap, sheet); + } + } + } + } + for (Integer index : sets) { + sheet.addMergedRegion(new CellRangeAddress(mergeDataMap.get(index) + .getStartRow(), mergeDataMap.get(index).getEndRow(), index, + index)); + } + + } + + /** + * 字符为空的情况下判断 + * + * @param index + * @param mergeDataMap + * @param sheet + */ + private void mergeCellOrContinue(Integer index, + Map mergeDataMap, Sheet sheet) { + if (mergeDataMap.containsKey(index) + && mergeDataMap.get(index).getEndRow() != mergeDataMap.get( + index).getStartRow()) { + sheet.addMergedRegion(new CellRangeAddress(mergeDataMap.get(index) + .getStartRow(), mergeDataMap.get(index).getEndRow(), index, + index)); + mergeDataMap.remove(index); + } + } + + /** + * 处理合并单元格 + * + * @param index + * @param rowNum + * @param text + * @param mergeDataMap + * @param sheet + * @param cell + * @param delys + */ + private void hanlderMergeCells(Integer index, int rowNum, String text, + Map mergeDataMap, Sheet sheet, Cell cell, + int[] delys) { + if (mergeDataMap.containsKey(index)) { + if (checkIsEqualByCellContents(mergeDataMap.get(index), text, cell, + delys, rowNum)) { + mergeDataMap.get(index).setEndRow(rowNum); + } else { + sheet.addMergedRegion(new CellRangeAddress(mergeDataMap.get( + index).getStartRow(), mergeDataMap.get(index) + .getEndRow(), index, index)); + mergeDataMap.put(index, + createMergeEntity(text, rowNum, cell, delys)); + } + } else { + mergeDataMap.put(index, + createMergeEntity(text, rowNum, cell, delys)); + } + } + + /** + * 获取一个单元格的值,确保这个单元格必须有值,不然向上查询 + * + * @param cell + * @param index + * @param rowNum + * @return + */ + private String getCellNotNullText(Cell cell, int index, int rowNum) { + String temp = cell.getRow().getCell(index).getStringCellValue(); + while (StringUtils.isEmpty(temp)) { + temp = cell.getRow().getSheet().getRow(--rowNum).getCell(index) + .getStringCellValue(); + } + return temp; + } + + private MergeEntity createMergeEntity(String text, int rowNum, Cell cell, + int[] delys) { + MergeEntity mergeEntity = new MergeEntity(text, rowNum, rowNum); + List list = new ArrayList(delys.length); + mergeEntity.setRelyList(list); + for (int i = 0; i < delys.length; i++) { + list.add(getCellNotNullText(cell, delys[i], rowNum)); + } + return mergeEntity; + } + + private boolean checkIsEqualByCellContents(MergeEntity mergeEntity, + String text, Cell cell, int[] delys, int rowNum) { + // 没有依赖关系 + if (delys == null || delys.length == 0) { + return mergeEntity.getText().equals(text); + } + // 存在依赖关系 + if (mergeEntity.getText().equals(text)) { + for (int i = 0; i > delys.length; i++) { + if (!getCellNotNullText(cell, delys[i], rowNum).equals( + mergeEntity.getRelyList().get(i))) { + return false; + } + } + return true; + } + return false; + } + + private Map getMergeDataMap( + List excelParams) { + Map mergeMap = new HashMap(); + // 设置参数顺序,为之后合并单元格做准备 + int i = 0; + for (ExcelExportEntity entity : excelParams) { + if (entity.isMergeVertical()) { + mergeMap.put(i, entity.getMergeRely()); + } + if (entity.getList() != null) { + for (ExcelExportEntity inner : entity.getList()) { + if (inner.isMergeVertical()) { + mergeMap.put(i, inner.getMergeRely()); + } + i++; + } + } else { + i++; + } + } + return mergeMap; + } + + /** + * 创建 最主要的 Cells + * + * @param styles + * @param rowHeight + * @throws Exception + */ + public int createCells(Drawing patriarch, int index, Object t, + List excelParams, Sheet sheet, + Workbook workbook, Map styles, + short rowHeight) throws Exception { + ExcelExportEntity entity; + Row row = sheet.createRow(index); + row.setHeight(rowHeight); + int maxHeight = 1, cellNum = 0; + for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) { + entity = excelParams.get(k); + if (entity.getList() != null) { + Collection list = (Collection) entity.getMethod().invoke( + t, new Object[] {}); + int listC = 0; + for (Object obj : list) { + createListCells(patriarch, index + listC, cellNum, obj, + entity.getList(), sheet, workbook, styles); + listC++; + } + cellNum += entity.getList().size(); + if (list != null && list.size() > maxHeight) { + maxHeight = list.size(); + } + } else { + Object value = getCellValue(entity, t); + if (entity.getType() == 1) { + createStringCell( + row, + cellNum++, + value == null ? "" : value.toString(), + index % 2 == 0 ? getStyles(styles, false, + entity.isWrap()) : getStyles(styles, true, + entity.isWrap()), entity); + } else { + createImageCell(patriarch, entity, row, cellNum++, + value == null ? "" : value.toString(), t); + } + } + } + // 合并需要合并的单元格 + cellNum = 0; + for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) { + entity = excelParams.get(k); + if (entity.getList() != null) { + cellNum += entity.getList().size(); + } else if (entity.isNeedMerge()) { + sheet.addMergedRegion(new CellRangeAddress(index, index + + maxHeight - 1, cellNum, cellNum)); + cellNum++; + } + } + return maxHeight; + + } + + public CellStyle getStyles(Map styles, boolean b, + boolean wrap) { + return null; + } + + /** + * 获取填如这个cell的值,提供一些附加功能 + * + * @param entity + * @param obj + * @return + * @throws Exception + */ + public Object getCellValue(ExcelExportEntity entity, Object obj) + throws Exception { + Object value = entity.getMethods() != null ? getFieldBySomeMethod( + entity.getMethods(), obj) : entity.getMethod().invoke(obj, + new Object[] {}); + if (needHanlderList != null + && needHanlderList.contains(entity.getName())) { + value = dataHanlder.exportHandler(obj, entity.getName(), value); + } else if (StringUtils.isNotEmpty(entity.getFormat())) { + value = formatValue(value, entity); + } else if (entity.getReplace() != null + && entity.getReplace().length > 0) { + value = replaceValue(entity.getReplace(), String.valueOf(value)); + } + return value == null ? "" : value.toString(); + } + + private Object replaceValue(String[] replace, String value) { + String[] temp; + for (String str : replace) { + temp = str.split("_"); + if (value.equals(temp[1])) { + value = temp[0]; + break; + } + } + return value; + } + + private Object formatValue(Object value, ExcelExportEntity entity) + throws Exception { + Date temp = null; + if (value instanceof String) { + SimpleDateFormat format = new SimpleDateFormat( + entity.getDatabaseFormat()); + temp = format.parse(value.toString()); + } else if (value instanceof Date) { + temp = (Date) value; + } + if (temp != null) { + SimpleDateFormat format = new SimpleDateFormat(entity.getFormat()); + value = format.format(temp); + } + return value; + } + + /** + * 创建List之后的各个Cells + * + * @param styles + */ + public void createListCells(Drawing patriarch, int index, int cellNum, + Object obj, List excelParams, Sheet sheet, + Workbook workbook, Map styles) + throws Exception { + ExcelExportEntity entity; + Row row; + if (sheet.getRow(index) == null) { + row = sheet.createRow(index); + row.setHeight(getRowHeight(excelParams)); + } else { + row = sheet.getRow(index); + } + for (int k = 0, paramSize = excelParams.size(); k < paramSize; k++) { + entity = excelParams.get(k); + Object value = getCellValue(entity, obj); + if (entity.getType() == 1) { + createStringCell( + row, + cellNum++, + value == null ? "" : value.toString(), + row.getRowNum() % 2 == 0 ? getStyles(styles, false, + entity.isWrap()) : getStyles(styles, true, + entity.isWrap()), entity); + } else { + createImageCell(patriarch, entity, row, cellNum++, + value == null ? "" : value.toString(), obj); + } + } + } + + public short getRowHeight(List excelParams) { + int maxHeight = 0; + for (int i = 0; i < excelParams.size(); i++) { + maxHeight = maxHeight > excelParams.get(i).getHeight() ? maxHeight + : excelParams.get(i).getHeight(); + if (excelParams.get(i).getList() != null) { + for (int j = 0; j < excelParams.get(i).getList().size(); j++) { + maxHeight = maxHeight > excelParams.get(i).getList().get(j) + .getHeight() ? maxHeight : excelParams.get(i) + .getList().get(j).getHeight(); + } + } + } + return (short) (maxHeight * 50); + } + + /** + * 对字段根据用户设置排序 + */ + public void sortAllParams(List excelParams) { + Collections.sort(excelParams, new ComparatorExcelField()); + for (ExcelExportEntity entity : excelParams) { + if (entity.getList() != null) { + Collections.sort(entity.getList(), new ComparatorExcelField()); + } + } + } + + /** + * 多个反射获取值 + * + * @param list + * @param t + * @return + * @throws Exception + */ + public Object getFieldBySomeMethod(List list, Object t) + throws Exception { + for (Method m : list) { + if (t == null) { + t = ""; + break; + } + t = m.invoke(t, new Object[] {}); + } + return t; + } + + public void setCellWith(List excelParams, Sheet sheet) { + int index = 0; + for (int i = 0; i < excelParams.size(); i++) { + if (excelParams.get(i).getList() != null) { + List list = excelParams.get(i).getList(); + for (int j = 0; j < list.size(); j++) { + sheet.setColumnWidth(index, 256 * list.get(j).getWidth()); + index++; + } + } else { + sheet.setColumnWidth(index, 256 * excelParams.get(i).getWidth()); + index++; + } + } + } + + /** + * 创建文本类型的Cell + * + * @param row + * @param index + * @param text + * @param style + * @param entity + */ + public void createStringCell(Row row, int index, String text, + CellStyle style, ExcelExportEntity entity) { + Cell cell = row.createCell(index); + RichTextString Rtext = new HSSFRichTextString(text); + cell.setCellValue(Rtext); + if (style != null) { + cell.setCellStyle(style); + } + } + + /** + * 图片类型的Cell + * + * @param patriarch + * @param entity + * @param row + * @param i + * @param string + * @param obj + * @throws Exception + */ + public void createImageCell(Drawing patriarch, ExcelExportEntity entity, + Row row, int i, String string, Object obj) throws Exception { + row.setHeight((short) (50 * entity.getHeight())); + row.createCell(i); + HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) i, + row.getRowNum(), (short) (i + 1), row.getRowNum() + 1); + if (StringUtils.isEmpty(string)) { + return; + } + if (entity.getExportImageType() == 1) { + ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); + BufferedImage bufferImg; + try { + String path = ExcelPublicUtil.getWebRootPath(string); + path = path.replace("WEB-INF/classes/", ""); + path = path.replace("file:/", ""); + bufferImg = ImageIO.read(new File(path)); + ImageIO.write( + bufferImg, + string.substring(string.indexOf(".") + 1, + string.length()), byteArrayOut); + byte[] value = byteArrayOut.toByteArray(); + patriarch.createPicture(anchor, row.getSheet().getWorkbook() + .addPicture(value, getImageType(value))); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + byte[] value = (byte[]) (entity.getMethods() != null ? getFieldBySomeMethod( + entity.getMethods(), obj) : entity.getMethod().invoke(obj, + new Object[] {})); + if (value != null) { + patriarch.createPicture(anchor, row.getSheet().getWorkbook() + .addPicture(value, getImageType(value))); + } + } + + } + + /** + * 获取图片类型,设置图片插入类型 + * + * @param value + * @return + * @Author JueYue + * @date 2013年11月25日 + */ + public int getImageType(byte[] value) { + String type = ExcelPublicUtil.getFileExtendName(value); + if (type.equalsIgnoreCase("JPG")) { + return HSSFWorkbook.PICTURE_TYPE_JPEG; + } else if (type.equalsIgnoreCase("PNG")) { + return HSSFWorkbook.PICTURE_TYPE_PNG; + } + return HSSFWorkbook.PICTURE_TYPE_JPEG; + } + + /** + * 获取导出报表的字段总长度 + * + * @param excelParams + * @return + */ + public int getFieldWidth(List excelParams) { + int length = -1;// 从0开始计算单元格的 + for (ExcelExportEntity entity : excelParams) { + length += entity.getList() != null ? entity.getList().size() : 1; + } + return length; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportServer.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportServer.java new file mode 100644 index 0000000..440d240 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportServer.java @@ -0,0 +1,300 @@ +package org.jeecgframework.poi.excel.export; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFDataFormat; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.util.CellRangeAddress; +import org.jeecgframework.poi.excel.annotation.ExcelTarget; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; +import org.jeecgframework.poi.exception.excel.ExcelExportException; +import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; +import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Excel导出服务 + * + * @author JueYue + * @date 2014年6月17日 下午5:30:54 + */ +public class ExcelExportServer extends ExcelExportBase { + + private final static Logger logger = LoggerFactory.getLogger(ExcelExportServer.class); + + private static final short cellFormat = HSSFDataFormat + .getBuiltinFormat("TEXT"); + + // 最大行数,超过自动多Sheet + private final int MAX_NUM = 60000; + + public void createSheet(HSSFWorkbook workbook, ExportParams entity, + Class pojoClass, Collection dataSet) { + if(logger.isDebugEnabled()){ + logger.debug("Excel export start ,class is {}",pojoClass); + } + if (workbook == null || entity == null || pojoClass == null + || dataSet == null) { + throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR); + } + Sheet sheet = null; + try { + sheet = workbook.createSheet(entity.getSheetName()); + } catch (Exception e) { + // 重复遍历,出现了重名现象,创建非指定的名称Sheet + sheet = workbook.createSheet(); + } + try { + dataHanlder = entity.getDataHanlder(); + if (dataHanlder != null) { + needHanlderList = Arrays.asList(dataHanlder + .getNeedHandlerFields()); + } + // 创建表格属性 + Map styles = createStyles(workbook); + Drawing patriarch = sheet.createDrawingPatriarch(); + List excelParams = new ArrayList(); + // 得到所有字段 + Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); + String targetId = etarget == null ? null : etarget.value(); + getAllExcelField(entity.getExclusions(), targetId, fileds, + excelParams, pojoClass, null); + sortAllParams(excelParams); + int index = createHeaderAndTitle(entity, sheet, workbook, + excelParams); + int titleHeight = index; + setCellWith(excelParams, sheet); + short rowHeight = getRowHeight(excelParams); + + Iterator its = dataSet.iterator(); + List tempList = new ArrayList(); + while (its.hasNext()) { + Object t = its.next(); + index += createCells(patriarch, index, t, excelParams, sheet, + workbook, styles, rowHeight); + tempList.add(t); + if (index >= MAX_NUM) + break; + } + mergeCells(sheet, excelParams, titleHeight); + + its = dataSet.iterator(); + for (int i = 0, le = tempList.size(); i < le; i++) { + its.next(); + its.remove(); + } + // 发现还有剩余list 继续循环创建Sheet + if (dataSet.size() > 0) { + createSheet(workbook, entity, pojoClass, dataSet); + } + + } catch (Exception e) { + e.printStackTrace(); + throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, + e.getCause()); + } + } + + private int createHeaderAndTitle(ExportParams entity, Sheet sheet, + HSSFWorkbook workbook, List excelParams) { + int rows = 0, feildWidth = getFieldWidth(excelParams); + if (entity.getTitle() != null) { + rows += createHeaderRow(entity, sheet, workbook, feildWidth); + } + rows += createTitleRow(entity, sheet, workbook, rows, excelParams); + sheet.createFreezePane(0, rows, 0, rows); + return rows; + } + + /** + * 创建表头 + * + * @param title + * @param index + */ + private int createTitleRow(ExportParams title, Sheet sheet, + HSSFWorkbook workbook, int index, + List excelParams) { + Row row = sheet.createRow(index); + int rows = getRowNums(excelParams); + row.setHeight((short) 450); + Row listRow = null; + if (rows == 2) { + listRow = sheet.createRow(index + 1); + listRow.setHeight((short) 450); + } + int cellIndex = 0; + CellStyle titleStyle = getTitleStyle(workbook, title); + for (int i = 0, exportFieldTitleSize = excelParams.size(); i < exportFieldTitleSize; i++) { + ExcelExportEntity entity = excelParams.get(i); + createStringCell(row, cellIndex, entity.getName(), titleStyle, + entity); + if (entity.getList() != null) { + List sTitel = entity.getList(); + sheet.addMergedRegion(new CellRangeAddress(index, index, + cellIndex, cellIndex + sTitel.size() - 1)); + for (int j = 0, size = sTitel.size(); j < size; j++) { + createStringCell(listRow, cellIndex, sTitel.get(j) + .getName(), titleStyle, entity); + cellIndex++; + } + } else if (rows == 2) { + sheet.addMergedRegion(new CellRangeAddress(index, index + 1, + cellIndex, cellIndex)); + } + cellIndex++; + } + return rows; + + } + + /** + * 判断表头是只有一行还是两行 + * + * @param excelParams + * @return + */ + private int getRowNums(List excelParams) { + for (int i = 0; i < excelParams.size(); i++) { + if (excelParams.get(i).getList() != null) { + return 2; + } + } + return 1; + } + + /** + * 创建 表头改变 + * + * @param entity + * @param sheet + * @param workbook + * @param feildWidth + */ + public int createHeaderRow(ExportParams entity, Sheet sheet, + HSSFWorkbook workbook, int feildWidth) { + Row row = sheet.createRow(0); + row.setHeight(entity.getTitleHeight()); + createStringCell(row, 0, entity.getTitle(), + getHeaderStyle(workbook, entity), null); + sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, feildWidth)); + if (entity.getSecondTitle() != null) { + row = sheet.createRow(1); + row.setHeight(entity.getSecondTitleHeight()); + HSSFCellStyle style = workbook.createCellStyle(); + style.setAlignment(HSSFCellStyle.ALIGN_RIGHT); + createStringCell(row, 0, entity.getSecondTitle(), style, null); + sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, feildWidth)); + return 2; + } + return 1; + } + + /** + * 字段说明的Style + * + * @param workbook + * @return + */ + public HSSFCellStyle getTitleStyle(HSSFWorkbook workbook, + ExportParams entity) { + HSSFCellStyle titleStyle = workbook.createCellStyle(); + titleStyle.setFillForegroundColor(entity.getHeaderColor()); // 填充的背景颜色 + titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充图案 + titleStyle.setWrapText(true); + return titleStyle; + } + + /** + * 表明的Style + * + * @param workbook + * @return + */ + public HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook, + ExportParams entity) { + HSSFCellStyle titleStyle = workbook.createCellStyle(); + Font font = workbook.createFont(); + font.setFontHeightInPoints((short) 24); + titleStyle.setFont(font); + titleStyle.setFillForegroundColor(entity.getColor()); + titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); + titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + return titleStyle; + } + + public HSSFCellStyle getTwoStyle(HSSFWorkbook workbook, boolean isWarp) { + HSSFCellStyle style = workbook.createCellStyle(); + style.setBorderLeft((short) 1); // 左边框 + style.setBorderRight((short) 1); // 右边框 + style.setBorderBottom((short) 1); + style.setBorderTop((short) 1); + style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index); // 填充的背景颜色 + style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 填充图案 + style.setAlignment(HSSFCellStyle.ALIGN_CENTER); + style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + style.setDataFormat(cellFormat); + if (isWarp) { + style.setWrapText(true); + } + return style; + } + + public HSSFCellStyle getOneStyle(HSSFWorkbook workbook, boolean isWarp) { + HSSFCellStyle style = workbook.createCellStyle(); + style.setBorderLeft((short) 1); // 左边框 + style.setBorderRight((short) 1); // 右边框 + style.setBorderBottom((short) 1); + style.setBorderTop((short) 1); + style.setAlignment(HSSFCellStyle.ALIGN_CENTER); + style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + style.setDataFormat(cellFormat); + if (isWarp) { + style.setWrapText(true); + } + return style; + } + + private Map createStyles(HSSFWorkbook workbook) { + Map map = new HashMap(); + map.put("one", getOneStyle(workbook, false)); + map.put("oneWrap", getOneStyle(workbook, true)); + map.put("two", getTwoStyle(workbook, false)); + map.put("twoWrap", getTwoStyle(workbook, true)); + return map; + } + + public CellStyle getStyles(Map map, boolean needOne, + boolean isWrap) { + if (needOne && isWrap) { + return map.get("oneWrap"); + } + if (needOne) { + return map.get("one"); + } + if (needOne == false && isWrap) { + return map.get("twoWrap"); + } + return map.get("two"); + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/template/ExcelExportOfTemplateUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/template/ExcelExportOfTemplateUtil.java new file mode 100644 index 0000000..b9e783a --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/template/ExcelExportOfTemplateUtil.java @@ -0,0 +1,268 @@ +package org.jeecgframework.poi.excel.export.template; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.jeecgframework.poi.cache.ExcelCache; +import org.jeecgframework.poi.excel.annotation.ExcelTarget; +import org.jeecgframework.poi.excel.entity.TemplateExportParams; +import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; +import org.jeecgframework.poi.excel.export.ExcelExportBase; +import org.jeecgframework.poi.exception.excel.ExcelExportException; +import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; +import org.jeecgframework.poi.util.ExcelPublicUtil; + +/** + * Excel 导出根据模板导出 + * + * @author JueYue + * @date 2013-10-17 + * @version 1.0 + */ +public final class ExcelExportOfTemplateUtil extends ExcelExportBase { + + public Workbook createExcleByTemplate(TemplateExportParams params, + Class pojoClass, Collection dataSet, Map map) { + // step 1. 判断模板的地址 + if (params == null || map == null + || StringUtils.isEmpty(params.getTemplateUrl())) { + throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR); + } + Workbook wb = null; + // step 2. 判断模板的Excel类型,解析模板 + try { + wb = getCloneWorkBook(params); + // step 3. 删除其他的sheet + for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) { + if (i != params.getSheetNum()) { + wb.removeSheetAt(i); + } + } + if (StringUtils.isNotEmpty(params.getSheetName())) { + wb.setSheetName(0, params.getSheetName()); + } + // step 4. 解析模板 + parseTemplate(wb.getSheetAt(0), map); + if (dataSet != null) { + // step 5. 正常的数据填充 + dataHanlder = params.getDataHanlder(); + if (dataHanlder != null) { + needHanlderList = Arrays.asList(dataHanlder + .getNeedHandlerFields()); + } + addDataToSheet(params, pojoClass, dataSet, wb.getSheetAt(0), wb); + } + } catch (Exception e) { + e.printStackTrace(); + return null; + } + return wb; + } + + /** + * 克隆excel防止操作原对象,workbook无法克隆,只能对excel进行克隆 + * + * @param params + * @throws Exception + * @Author JueYue + * @date 2013-11-11 + */ + private Workbook getCloneWorkBook(TemplateExportParams params) + throws Exception { + return ExcelCache.getWorkbook(params.getTemplateUrl(), + params.getSheetNum()); + + } + + /** + * 往Sheet 填充正常数据,根据表头信息 使用导入的部分逻辑,坐对象映射 + * + * @param params + * @param pojoClass + * @param dataSet + * @param workbook + */ + private void addDataToSheet(TemplateExportParams params, + Class pojoClass, Collection dataSet, Sheet sheet, + Workbook workbook) throws Exception { + // 获取表头数据 + Map titlemap = getTitleMap(params, sheet); + Drawing patriarch = sheet.createDrawingPatriarch(); + // 得到所有字段 + Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); + String targetId = null; + if (etarget != null) { + targetId = etarget.value(); + } + // 获取实体对象的导出数据 + List excelParams = new ArrayList(); + getAllExcelField(null, targetId, fileds, excelParams, pojoClass, null); + // 根据表头进行筛选排序 + sortAndFilterExportField(excelParams, titlemap); + short rowHeight = getRowHeight(excelParams); + Iterator its = dataSet.iterator(); + int index = sheet.getLastRowNum() + 1, titleHeight = index; + while (its.hasNext()) { + Object t = its.next(); + index += createCells(patriarch, index, t, excelParams, sheet, + workbook, null, rowHeight); + } + // 合并同类项 + mergeCells(sheet, excelParams, titleHeight); + } + + /** + * 对导出序列进行排序和塞选 + * + * @param excelParams + * @param titlemap + * @return + */ + private void sortAndFilterExportField(List excelParams, + Map titlemap) { + for (int i = excelParams.size() - 1; i >= 0; i--) { + if (excelParams.get(i).getList() != null + && excelParams.get(i).getList().size() > 0) { + sortAndFilterExportField(excelParams.get(i).getList(), titlemap); + if (excelParams.get(i).getList().size() == 0) { + excelParams.remove(i); + } else { + excelParams.get(i).setOrderNum(i); + } + } else { + if (titlemap.containsKey(excelParams.get(i).getName())) { + excelParams.get(i).setOrderNum(i); + } else { + excelParams.remove(i); + } + } + } + sortAllParams(excelParams); + } + + /** + * 获取表头数据,设置表头的序号 + * + * @param params + * @param sheet + * @return + */ + private Map getTitleMap(TemplateExportParams params, + Sheet sheet) { + Row row = null; + Iterator cellTitle; + Map titlemap = new HashMap(); + for (int j = 0; j < params.getHeadingRows(); j++) { + row = sheet.getRow(j + params.getHeadingStartRow()); + cellTitle = row.cellIterator(); + int i = row.getFirstCellNum(); + while (cellTitle.hasNext()) { + Cell cell = cellTitle.next(); + String value = cell.getStringCellValue(); + if (!StringUtils.isEmpty(value)) { + titlemap.put(value, i); + } + i = i + 1; + } + } + return titlemap; + + } + + private void parseTemplate(Sheet sheet, Map map) + throws Exception { + Iterator rows = sheet.rowIterator(); + Row row; + while (rows.hasNext()) { + row = rows.next(); + for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { + setValueForCellByMap(row.getCell(i), map); + } + } + } + + /** + * 给每个Cell通过解析方式set值 + * + * @param cell + * @param map + */ + private void setValueForCellByMap(Cell cell, Map map) + throws Exception { + String oldString; + try {// step 1. 判断这个cell里面是不是函数 + oldString = cell.getStringCellValue(); + } catch (Exception e) { + return; + } + if (oldString != null && oldString.indexOf("{{") != -1) { + // setp 2. 判断是否含有解析函数 + String params; + while (oldString.indexOf("{{") != -1) { + params = oldString.substring(oldString.indexOf("{{") + 2, + oldString.indexOf("}}")); + oldString = oldString.replace("{{" + params + "}}", + getParamsValue(params.trim(), map)); + } + cell.setCellValue(oldString); + } + } + + /** + * 获取参数值 + * + * @param params + * @param map + * @return + */ + private String getParamsValue(String params, Map map) + throws Exception { + if (params.indexOf(".") != -1) { + String[] paramsArr = params.split("\\."); + return getValueDoWhile(map.get(paramsArr[0]), paramsArr, 1); + } + return map.containsKey(params) ? map.get(params).toString() : ""; + } + + /** + * 通过遍历过去对象值 + * + * @param object + * @param paramsArr + * @param index + * @return + * @throws Exception + * @throws java.lang.reflect.InvocationTargetException + * @throws IllegalAccessException + * @throws IllegalArgumentException + */ + @SuppressWarnings("rawtypes") + private String getValueDoWhile(Object object, String[] paramsArr, int index) + throws Exception { + if (object == null) { + return ""; + } + if (object instanceof Map) { + object = ((Map) object).get(paramsArr[index]); + } else { + object = ExcelPublicUtil.getMethod(paramsArr[index], + object.getClass()).invoke(object, new Object[] {}); + } + return (index == paramsArr.length - 1) ? (object == null ? "" : object + .toString()) : getValueDoWhile(object, paramsArr, ++index); + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/CellValueServer.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/CellValueServer.java new file mode 100644 index 0000000..96da100 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/CellValueServer.java @@ -0,0 +1,187 @@ +package org.jeecgframework.poi.excel.imports; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.ss.usermodel.Cell; +import org.jeecgframework.poi.excel.entity.params.ExcelImportEntity; +import org.jeecgframework.poi.exception.excel.ExcelImportException; +import org.jeecgframework.poi.exception.excel.enums.ExcelImportEnum; +import org.jeecgframework.poi.handler.inter.IExcelDataHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Cell 取值服务 + * 判断类型处理数据 1.判断Excel中的类型 2.根据replace替换值 3.handler处理数据 4.判断返回类型转化数据返回 + * + * @author JueYue + * @date 2014年6月26日 下午10:42:28 + */ +public class CellValueServer { + + private static final Logger logger = LoggerFactory + .getLogger(CellValueServer.class); + + private List hanlderList = null; + + /** + * 获取cell的值 + * + * @param object + * @param excelParams + * @param cell + * @param titleString + */ + public Object getValue(IExcelDataHandler dataHanlder, Object object, + Cell cell, Map excelParams, + String titleString) throws Exception { + ExcelImportEntity entity = excelParams.get(titleString); + Method setMethod = entity.getMethods() != null + && entity.getMethods().size() > 0 ? entity.getMethods().get( + entity.getMethods().size() - 1) : entity.getMethod(); + Type[] ts = setMethod.getGenericParameterTypes(); + String xclass = ts[0].toString(); + Object result = getCellValue(xclass, cell, entity); + result = replaceValue(entity.getReplace(), result); + result = hanlderValue(dataHanlder, object, result, titleString); + return getValueByType(xclass, result); + } + + /** + * 根据返回类型获取返回值 + * + * @param xclass + * @param result + * @return + */ + private Object getValueByType(String xclass, Object result) { + try { + if (xclass.equals("class java.util.Date")) { + return result; + } + if (xclass.equals("class java.lang.Boolean") + || xclass.equals("boolean")) { + return Boolean.valueOf(String.valueOf(result)); + } + if (xclass.equals("class java.lang.Double") || xclass.equals("double")) { + return Double.valueOf(String.valueOf(result)); + } + if (xclass.equals("class java.lang.Long") || xclass.equals("long")) { + return Long.valueOf(String.valueOf(result)); + } + if (xclass.equals("class java.lang.Integer") || xclass.equals("int")) { + return Integer.valueOf(String.valueOf(result)); + } + return String.valueOf(result); + } catch (NumberFormatException e) { + e.printStackTrace(); + throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR); + } + } + + /** + * 调用处理接口处理值 + * + * @param dataHanlder + * @param object + * @param result + * @param titleString + * @return + */ + private Object hanlderValue(IExcelDataHandler dataHanlder, Object object, + Object result, String titleString) { + if (dataHanlder == null) { + return result; + } + if (hanlderList == null) { + hanlderList = Arrays.asList(dataHanlder.getNeedHandlerFields()); + } + if (hanlderList.contains(titleString)) { + return dataHanlder.importHandler(object, titleString, result); + } + return result; + } + + /** + * 替换值 + * + * @param replace + * @param result + * @return + */ + private Object replaceValue(String[] replace, Object result) { + if (replace != null && replace.length > 0) { + String temp = String.valueOf(result); + String[] tempArr; + for (int i = 0; i < replace.length; i++) { + tempArr = replace[i].split("_"); + if (temp.equals(tempArr[0])) { + return tempArr[1]; + } + } + } + return result; + } + + /** + * 获取单元格内的值 + * + * @param xclass + * @param cell + * @param entity + * @return + */ + private Object getCellValue(String xclass, Cell cell, + ExcelImportEntity entity) { + Object result = null; + // 日期格式比较特殊,和cell格式不一致 + if (xclass.equals("class java.util.Date")) { + if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { + // 日期格式 + result = cell.getDateCellValue(); + } else { + cell.setCellType(Cell.CELL_TYPE_STRING); + result = getDateData(entity, cell.getStringCellValue()); + } + } else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) { + result = cell.getNumericCellValue(); + }else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) { + result = cell.getBooleanCellValue(); + } else { + cell.setCellType(Cell.CELL_TYPE_STRING); + result = cell.getStringCellValue(); + } + return result; + } + + /** + * 获取日期类型数据 + * + * @Author JueYue + * @date 2013年11月26日 + * @param entity + * @param value + * @return + */ + private Date getDateData(ExcelImportEntity entity, String value) { + if (StringUtils.isNotEmpty(entity.getFormat()) + && StringUtils.isNotEmpty(value)) { + SimpleDateFormat format = new SimpleDateFormat(entity.getFormat()); + try { + return format.parse(value); + } catch (ParseException e) { + logger.error("时间格式化失败,格式化:{},值:{}", entity.getFormat(), value); + throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR); + } + } + return null; + } +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/ExcelImportServer.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/ExcelImportServer.java new file mode 100644 index 0000000..e26621f --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/ExcelImportServer.java @@ -0,0 +1,591 @@ +package org.jeecgframework.poi.excel.imports; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.PushbackInputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.apache.poi.POIXMLDocument; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.formula.functions.T; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.PictureData; +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.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.jeecgframework.poi.excel.annotation.Excel; +import org.jeecgframework.poi.excel.annotation.ExcelTarget; +import org.jeecgframework.poi.excel.annotation.ExcelVerify; +import org.jeecgframework.poi.excel.entity.ImportParams; +import org.jeecgframework.poi.excel.entity.params.ExcelCollectionParams; +import org.jeecgframework.poi.excel.entity.params.ExcelImportEntity; +import org.jeecgframework.poi.excel.entity.params.ExcelVerifyEntity; +import org.jeecgframework.poi.excel.entity.result.ExcelImportResult; +import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; +import org.jeecgframework.poi.excel.imports.verifys.VerifyHandlerServer; +import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Excel 导入服务 + * + * @author JueYue + * @date 2014年6月26日 下午9:20:51 + */ +@SuppressWarnings({ "rawtypes", "unchecked", "hiding" }) +public class ExcelImportServer { + + private final static Logger logger = LoggerFactory.getLogger(ExcelImportServer.class); + + private CellValueServer cellValueServer; + + private VerifyHandlerServer verifyHandlerServer; + + private boolean verfiyFail = false; + + public ExcelImportServer() { + cellValueServer = new CellValueServer(); + verifyHandlerServer = new VerifyHandlerServer(); + } + + /** + * Excel 导入 field 字段类型 Integer,Long,Double,Date,String,Boolean + * + * @param inputstream + * @param pojoClass + * @param params + * @return + * @throws Exception + */ + public ExcelImportResult importExcelByIs(InputStream inputstream, + Class pojoClass, ImportParams params) throws Exception { + if(logger.isDebugEnabled()){ + logger.debug("Excel import start ,class is {}",pojoClass); + } + List result = new ArrayList(); + Workbook book = null; + boolean isXSSFWorkbook = true; + if (!(inputstream.markSupported())) { + inputstream = new PushbackInputStream(inputstream, 8); + } + if (POIFSFileSystem.hasPOIFSHeader(inputstream)) { + book = new HSSFWorkbook(inputstream); + isXSSFWorkbook = false; + } else if (POIXMLDocument.hasOOXMLHeader(inputstream)) { + book = new XSSFWorkbook(OPCPackage.open(inputstream)); + } + Map pictures; + for (int i = 0; i < params.getSheetNum(); i++) { + if (isXSSFWorkbook) { + pictures = ExcelPublicUtil.getSheetPictrues07( + (XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book); + } else { + pictures = ExcelPublicUtil.getSheetPictrues03( + (HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book); + } + result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, + params, pictures)); + } + if (params.isNeedSave()) { + saveThisExcel(params, pojoClass, isXSSFWorkbook, book); + } + return new ExcelImportResult(result, verfiyFail, book); + } + + private void saveThisExcel(ImportParams params, Class pojoClass, + boolean isXSSFWorkbook, Workbook book) throws Exception { + String path = ExcelPublicUtil.getWebRootPath(getSaveExcelUrl(params, + pojoClass)); + File savefile = new File(path); + if (!savefile.exists()) { + savefile.mkdirs(); + } + SimpleDateFormat format = new SimpleDateFormat("yyyMMddHHmmss"); + FileOutputStream fos = new FileOutputStream(path + "/" + + format.format(new Date()) + "_" + + Math.round(Math.random() * 100000) + + (isXSSFWorkbook == true ? ".xlsx" : ".xls")); + book.write(fos); + fos.close(); + } + + /** + * 获取保存的Excel 的真实路径 + * + * @param params + * @param pojoClass + * @return + * @throws Exception + */ + private String getSaveExcelUrl(ImportParams params, Class pojoClass) + throws Exception { + String url = ""; + if (params.getSaveUrl().equals("upload/excelUpload")) { + url = pojoClass.getName().split("\\.")[pojoClass.getName().split( + "\\.").length - 1]; + return params.getSaveUrl() + "/" + + url.substring(0, url.lastIndexOf("Entity")); + } + return params.getSaveUrl(); + } + + private List importExcel(Collection result, Sheet sheet, + Class pojoClass, ImportParams params, + Map pictures) throws Exception { + List collection = new ArrayList(); + Map excelParams = new HashMap(); + List excelCollection = new ArrayList(); + Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); + String targetId = null; + if (etarget != null) { + targetId = etarget.value(); + } + getAllExcelField(targetId, fileds, excelParams, excelCollection, + pojoClass, null); + Iterator rows = sheet.rowIterator(); + for (int j = 0; j < params.getTitleRows(); j++) { + rows.next(); + } + Row row = null; + Iterator cellTitle; + Map titlemap = new HashMap(); + for (int j = 0; j < params.getHeadRows(); j++) { + row = rows.next(); + cellTitle = row.cellIterator(); + int i = row.getFirstCellNum(); + while (cellTitle.hasNext()) { + Cell cell = cellTitle.next(); + String value = cell.getStringCellValue(); + if (!StringUtils.isEmpty(value)) { + titlemap.put(i, value); + } + i = i + 1; + } + } + Object object = null; + String picId; + while (rows.hasNext()) { + row = rows.next(); + // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象 + if ((row.getCell(params.getKeyIndex()) == null || StringUtils + .isEmpty(getKeyValue(row.getCell(params.getKeyIndex())))) + && object != null) { + for (ExcelCollectionParams param : excelCollection) { + addListContinue(object, param, row, titlemap, targetId, + pictures, params); + } + } else { + object = ExcelPublicUtil.createObject(pojoClass, targetId); + for (int i = row.getFirstCellNum(), le = row.getLastCellNum(); i < le; i++) { + Cell cell = row.getCell(i); + String titleString = (String) titlemap.get(i); + if (excelParams.containsKey(titleString)) { + if (excelParams.get(titleString).getType() == 2) { + picId = row.getRowNum() + "_" + i; + saveImage(object, picId, excelParams, titleString, + pictures, params); + } else { + saveFieldValue(params, object, cell, excelParams, + titleString, row); + } + } + } + for (ExcelCollectionParams param : excelCollection) { + addListContinue(object, param, row, titlemap, targetId, + pictures, params); + } + collection.add(object); + } + } + return collection; + } + + /** + * 保存字段值(获取值,校验值,追加错误信息) + * + * @param params + * @param object + * @param cell + * @param excelParams + * @param titleString + * @param excelParams2 + * @param row + * @throws Exception + */ + private void saveFieldValue(ImportParams params, Object object, Cell cell, + Map excelParams, String titleString, + Row row) throws Exception { + ExcelVerifyHanlderResult verifyResult; + Object value = cellValueServer.getValue(params.getDataHanlder(), + object, cell, excelParams, titleString); + verifyResult = verifyHandlerServer.verifyData(object, value, + titleString, excelParams.get(titleString).getVerify(), + params.getVerifyHanlder()); + if (verifyResult.isSuccess()) { + setValues(excelParams.get(titleString), object, value); + } else { + Cell errorCell = row.createCell(row.getLastCellNum()); + errorCell.setCellValue(verifyResult.getMsg()); + verfiyFail = true; + } + } + + /** + * 获取key的值,针对不同类型获取不同的值 + * + * @Author JueYue + * @date 2013-11-21 + * @param cell + * @return + */ + private String getKeyValue(Cell cell) { + Object obj = null; + switch (cell.getCellType()) { + case Cell.CELL_TYPE_STRING: + obj = cell.getStringCellValue(); + break; + case Cell.CELL_TYPE_BOOLEAN: + obj = cell.getBooleanCellValue(); + break; + case Cell.CELL_TYPE_NUMERIC: + obj = cell.getNumericCellValue(); + break; + } + return obj == null ? null : obj.toString(); + } + + /** + * + * @param object + * @param picId + * @param excelParams + * @param titleString + * @param pictures + * @param params + * @throws Exception + */ + private void saveImage(Object object, String picId, + Map excelParams, String titleString, + Map pictures, ImportParams params) + throws Exception { + if (pictures == null) { + return; + } + PictureData image = pictures.get(picId); + byte[] data = image.getData(); + String fileName = "pic" + Math.round(Math.random() * 100000000000L); + fileName += "." + ExcelPublicUtil.getFileExtendName(data); + if (excelParams.get(titleString).getSaveType() == 1) { + String path = ExcelPublicUtil.getWebRootPath(getSaveUrl( + excelParams.get(titleString), object)); + File savefile = new File(path); + if (!savefile.exists()) { + savefile.mkdirs(); + } + savefile = new File(path + "/" + fileName); + FileOutputStream fos = new FileOutputStream(savefile); + fos.write(data); + fos.close(); + setValues(excelParams.get(titleString), object, + getSaveUrl(excelParams.get(titleString), object) + "/" + + fileName); + } else { + setValues(excelParams.get(titleString), object, data); + } + } + + /** + * 获取保存的真实路径 + * + * @param excelImportEntity + * @param object + * @return + * @throws Exception + */ + private String getSaveUrl(ExcelImportEntity excelImportEntity, Object object) + throws Exception { + String url = ""; + if (excelImportEntity.getSaveUrl().equals("upload")) { + if (excelImportEntity.getMethods() != null + && excelImportEntity.getMethods().size() > 0) { + object = getFieldBySomeMethod(excelImportEntity.getMethods(), + object); + } + url = object.getClass().getName().split("\\.")[object.getClass() + .getName().split("\\.").length - 1]; + return excelImportEntity.getSaveUrl() + "/" + + url.substring(0, url.lastIndexOf("Entity")); + } + return excelImportEntity.getSaveUrl(); + } + + /*** + * 向List里面继续添加元素 + * + * @param exclusions + * @param object + * @param param + * @param row + * @param titlemap + * @param targetId + * @param pictures + * @param params + */ + private void addListContinue(Object object, ExcelCollectionParams param, + Row row, Map titlemap, String targetId, + Map pictures, ImportParams params) + throws Exception { + Collection collection = (Collection) ExcelPublicUtil.getMethod( + param.getName(), object.getClass()).invoke(object, + new Object[] {}); + Object entity = ExcelPublicUtil.createObject(param.getType(), targetId); + String picId; + boolean isUsed = false;// 是否需要加上这个对象 + for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { + Cell cell = row.getCell(i); + String titleString = (String) titlemap.get(i); + if (param.getExcelParams().containsKey(titleString)) { + if (param.getExcelParams().get(titleString).getType() == 2) { + picId = row.getRowNum() + "_" + i; + saveImage(object, picId, param.getExcelParams(), + titleString, pictures, params); + } else { + saveFieldValue(params, entity, cell, + param.getExcelParams(), titleString, row); + } + isUsed = true; + } + } + if (isUsed) { + collection.add(entity); + } + } + + /** + * + * @param entity + * @param object + * @param value + * @throws Exception + */ + private void setValues(ExcelImportEntity entity, Object object, Object value) + throws Exception { + if (entity.getMethods() != null) { + setFieldBySomeMethod(entity.getMethods(), object, value); + } else { + entity.getMethod().invoke(object, value); + } + } + + /** + * 多个get 最后再set + * + * @param setMethods + * @param object + */ + private void setFieldBySomeMethod(List setMethods, Object object, + Object value) throws Exception { + Object t = getFieldBySomeMethod(setMethods, object); + setMethods.get(setMethods.size() - 1).invoke(t, value); + } + + private Object getFieldBySomeMethod(List list, Object t) + throws Exception { + Method m; + for (int i = 0; i < list.size() - 1; i++) { + m = list.get(i); + t = m.invoke(t, new Object[] {}); + } + return t; + } + + /** + * 获取需要导出的全部字段 + * + * + * @param exclusions + * @param targetId + * 目标ID + * @param fields + * @param excelCollection + * @throws Exception + */ + private void getAllExcelField(String targetId, Field[] fields, + Map excelParams, + List excelCollection, Class pojoClass, + List getMethods) throws Exception { + ExcelImportEntity excelEntity = null; + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + if (ExcelPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + continue; + } + if (ExcelPublicUtil.isCollection(field.getType())) { + // 集合对象设置属性 + ExcelCollectionParams collection = new ExcelCollectionParams(); + collection.setName(field.getName()); + Map temp = new HashMap(); + ParameterizedType pt = (ParameterizedType) field + .getGenericType(); + Class clz = (Class) pt.getActualTypeArguments()[0]; + collection.setType(clz); + getExcelFieldList(targetId, + ExcelPublicUtil.getClassFields(clz), clz, temp, null); + collection.setExcelParams(temp); + excelCollection.add(collection); + } else if (ExcelPublicUtil.isJavaClass(field)) { + addEntityToMap(targetId, field, excelEntity, pojoClass, + getMethods, excelParams); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + pojoClass)); + getAllExcelField(targetId, + ExcelPublicUtil.getClassFields(field.getType()), + excelParams, excelCollection, field.getType(), + newMethods); + } + } + } + + private void getExcelFieldList(String targetId, Field[] fields, + Class pojoClass, Map temp, + List getMethods) throws Exception { + ExcelImportEntity excelEntity = null; + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + if (ExcelPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + continue; + } + if (ExcelPublicUtil.isJavaClass(field)) { + addEntityToMap(targetId, field, excelEntity, pojoClass, + getMethods, temp); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + pojoClass, field.getType())); + getExcelFieldList(targetId, + ExcelPublicUtil.getClassFields(field.getType()), + field.getType(), temp, newMethods); + } + } + } + + /** + * 把这个注解解析放到类型对象中 + * + * @param targetId + * @param field + * @param excelEntity + * @param pojoClass + * @param getMethods + * @param temp + * @throws Exception + */ + private void addEntityToMap(String targetId, Field field, + ExcelImportEntity excelEntity, Class pojoClass, + List getMethods, Map temp) + throws Exception { + Excel excel = field.getAnnotation(Excel.class); + excelEntity = new ExcelImportEntity(); + excelEntity.setType(excel.type()); + excelEntity.setSaveUrl(excel.savePath()); + excelEntity.setSaveType(excel.imageType()); + excelEntity.setReplace(excel.replace()); + excelEntity.setDatabaseFormat(excel.databaseFormat()); + excelEntity.setVerify(getImportVerify(field)); + getExcelField(targetId, field, excelEntity, excel, pojoClass); + if (getMethods != null) { + List newMethods = new ArrayList(); + newMethods.addAll(getMethods); + newMethods.add(excelEntity.getMethod()); + excelEntity.setMethods(newMethods); + } + temp.put(excelEntity.getName(), excelEntity); + + } + + /** + * 获取导入校验参数 + * + * @param field + * @return + */ + private ExcelVerifyEntity getImportVerify(Field field) { + ExcelVerify verify = field.getAnnotation(ExcelVerify.class); + if (verify != null) { + ExcelVerifyEntity entity = new ExcelVerifyEntity(); + entity.setEmail(verify.isEmail()); + entity.setInterHandler(verify.interHandler()); + entity.setMaxLength(verify.maxLength()); + entity.setMinLength(verify.minLength()); + entity.setMobile(verify.isMobile()); + entity.setNotNull(verify.notNull()); + entity.setRegex(verify.regex()); + entity.setRegexTip(verify.regexTip()); + entity.setTel(verify.isTel()); + return entity; + } + return null; + } + + private void getExcelField(String targetId, Field field, + ExcelImportEntity excelEntity, Excel excel, Class pojoClass) + throws Exception { + excelEntity.setName(getExcelName(excel.name(), targetId)); + String fieldname = field.getName(); + excelEntity.setMethod(ExcelPublicUtil.getMethod(fieldname, pojoClass, + field.getType())); + if (StringUtils.isEmpty(excel.importFormat())) { + excelEntity.setFormat(excel.format()); + } else { + excelEntity.setFormat(excel.importFormat()); + } + } + + /** + * 判断在这个单元格显示的名称 + * + * @param exportName + * @param targetId + * @return + */ + private String getExcelName(String exportName, String targetId) { + if (exportName.indexOf("_") < 0) { + return exportName; + } + String[] arr = exportName.split(","); + for (String str : arr) { + if (str.indexOf(targetId) != -1) { + return str.split("_")[0]; + } + } + return null; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/package-info.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/package-info.java new file mode 100644 index 0000000..984e595 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/package-info.java @@ -0,0 +1,6 @@ +/** + * 导入类 + * @author JueYue + * @date 2014年6月23日 下午11:05:59 + */ +package org.jeecgframework.poi.excel.imports; \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/BaseVerifyHandler.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/BaseVerifyHandler.java new file mode 100644 index 0000000..b435173 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/BaseVerifyHandler.java @@ -0,0 +1,136 @@ +package org.jeecgframework.poi.excel.imports.verifys; + +import java.util.regex.Pattern; + +import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; + +/** + * 基础校验工具类 + * + * @author JueYue + * @date 2014年6月23日 下午11:10:12 + */ +public class BaseVerifyHandler { + + private static String NOT_NULL = "不允许为空"; + private static String IS_MOBILE = "不是手机号"; + private static String IS_TEL = "不是电话号码"; + private static String IS_EMAIL = "不是邮箱地址"; + private static String MIN_LENGHT = "小于规定长度"; + private static String MAX_LENGHT = "超过规定长度"; + + private static Pattern mobilePattern = Pattern + .compile("/^[+]{0,1}(\\d){1,3}[ ]?([-]?((\\d)|[ ]){1,12})+$/"); + + private static Pattern telPattern = Pattern + .compile("/^[+]{0,1}(\\d){1,3}[ ]?([-]?((\\d)|[ ]){1,12})+$/"); + + private static Pattern emailPattern = Pattern + .compile(" /^([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\\_|\\.]?)*[a-zA-Z0-9]+\\.[a-zA-Z]{2,3}$/"); + + /** + * 非空校验 + * + * @param name + * @param val + * @return + */ + public static ExcelVerifyHanlderResult notNull(String name, Object val) { + if (val == null) { + return new ExcelVerifyHanlderResult(false, name + NOT_NULL); + } + return new ExcelVerifyHanlderResult(true); + } + + /** + * 手机校验 + * + * @param name + * @param val + * @return + */ + public static ExcelVerifyHanlderResult isMobile(String name, Object val) { + if (!mobilePattern.matcher(String.valueOf(val)).matches()) { + return new ExcelVerifyHanlderResult(false, name + IS_MOBILE); + } + return new ExcelVerifyHanlderResult(true); + } + + /** + * 电话校验 + * + * @param name + * @param val + * @return + */ + public static ExcelVerifyHanlderResult isTel(String name, Object val) { + if (!telPattern.matcher(String.valueOf(val)).matches()) { + return new ExcelVerifyHanlderResult(false, name + IS_TEL); + } + return new ExcelVerifyHanlderResult(true); + } + + /** + * email校验 + * + * @param name + * @param val + * @return + */ + public static ExcelVerifyHanlderResult isEmail(String name, Object val) { + if (!emailPattern.matcher(String.valueOf(val)).matches()) { + return new ExcelVerifyHanlderResult(false, name + IS_EMAIL); + } + return new ExcelVerifyHanlderResult(true); + } + + /** + * 最小长度校验 + * + * @param name + * @param val + * @param minLength + * @return + */ + public static ExcelVerifyHanlderResult minLength(String name, Object val, + int minLength) { + if (notNull(name, val).isSuccess() + && String.valueOf(val).length() < minLength) { + return new ExcelVerifyHanlderResult(false, name + MIN_LENGHT); + } + return new ExcelVerifyHanlderResult(true); + } + + /** + * 最大长度校验 + * + * @param name + * @param val + * @return + */ + public static ExcelVerifyHanlderResult maxLength(String name, Object val, + int maxLength) { + if (notNull(name, val).isSuccess() + && String.valueOf(val).length() > maxLength) { + return new ExcelVerifyHanlderResult(false, name + MAX_LENGHT); + } + return new ExcelVerifyHanlderResult(true); + } + /** + * 正则表达式校验 + * @param name + * @param val + * @param regex + * @param regexTip + * @return + */ + public static ExcelVerifyHanlderResult regex(String name, Object val, + String regex, String regexTip) { + Pattern pattern = Pattern.compile(regex); + if (!pattern.matcher(String.valueOf(val)).matches()) { + return new ExcelVerifyHanlderResult(false, name + regexTip); + } + return new ExcelVerifyHanlderResult(true); + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/VerifyHandlerServer.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/VerifyHandlerServer.java new file mode 100644 index 0000000..a572dbc --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/imports/verifys/VerifyHandlerServer.java @@ -0,0 +1,73 @@ +package org.jeecgframework.poi.excel.imports.verifys; + +import org.apache.commons.lang.StringUtils; +import org.jeecgframework.poi.excel.entity.params.ExcelVerifyEntity; +import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; +import org.jeecgframework.poi.handler.inter.IExcelVerifyHandler; + +/** + * 校验服务 + * + * @author JueYue + * @date 2014年6月29日 下午4:37:56 + */ +public class VerifyHandlerServer { + /** + * 校驗數據 + * + * @param object + * @param value + * @param titleString + * @param verify + * @param iExcelVerifyHandler + */ + public ExcelVerifyHanlderResult verifyData(Object object, Object value, + String name, ExcelVerifyEntity verify, + IExcelVerifyHandler iExcelVerifyHandler) { + ExcelVerifyHanlderResult result = new ExcelVerifyHanlderResult(true, ""); + if (verify == null) { + return result; + } + if (verify.isEmail()) { + addVerifyResult(BaseVerifyHandler.isEmail(name, value), result); + } + if (verify.isInterHandler()) { + addVerifyResult( + iExcelVerifyHandler.verifyHandler(object, name, value), + result); + } + if (verify.isMobile()) { + addVerifyResult(BaseVerifyHandler.isMobile(name, value), result); + } + if (verify.isNotNull()) { + addVerifyResult(BaseVerifyHandler.notNull(name, value), result); + } + if (verify.isTel()) { + addVerifyResult(BaseVerifyHandler.isTel(name, value), result); + } + if (verify.getMaxLength() != -1) { + addVerifyResult( + BaseVerifyHandler.maxLength(name, value, + verify.getMaxLength()), result); + } + if (verify.getMinLength() != -1) { + addVerifyResult( + BaseVerifyHandler.minLength(name, value, + verify.getMinLength()), result); + } + if (StringUtils.isNotEmpty(verify.getRegex())) { + addVerifyResult(BaseVerifyHandler.regex(name, value, + verify.getRegex(), verify.getRegexTip()), result); + } + return result; + + } + + private void addVerifyResult(ExcelVerifyHanlderResult temp, + ExcelVerifyHanlderResult result) { + if (!temp.isSuccess()) { + result.setSuccess(false); + result.setMsg(result.getMsg() + temp.getMsg()); + } + } +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelExportException.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelExportException.java new file mode 100644 index 0000000..8408011 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelExportException.java @@ -0,0 +1,47 @@ +package org.jeecgframework.poi.exception.excel; + +import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; + +/** + * 导出异常 + * + * @author JueYue + * @date 2014年6月19日 下午10:56:18 + */ +public class ExcelExportException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private ExcelExportEnum type; + + public ExcelExportException() { + super(); + } + + public ExcelExportException(String message) { + super(message); + } + + public ExcelExportException(ExcelExportEnum type) { + super(type.getMsg()); + this.type = type; + } + + public ExcelExportException(String message, ExcelExportEnum type) { + super(message); + this.type = type; + } + + public ExcelExportException(ExcelExportEnum type, Throwable cause) { + super(type.getMsg(), cause); + } + + public ExcelExportEnum getType() { + return type; + } + + public void setType(ExcelExportEnum type) { + this.type = type; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelImportException.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelImportException.java new file mode 100644 index 0000000..70ac2bc --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/ExcelImportException.java @@ -0,0 +1,46 @@ +package org.jeecgframework.poi.exception.excel; + +import org.jeecgframework.poi.exception.excel.enums.ExcelImportEnum; + +/** + * 导入异常 + * @author JueYue + * @date 2014年6月29日 下午2:23:43 + */ +public class ExcelImportException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private ExcelImportEnum type; + + public ExcelImportException() { + super(); + } + + public ExcelImportException(String message) { + super(message); + } + + public ExcelImportException(ExcelImportEnum type) { + super(type.getMsg()); + this.type = type; + } + + public ExcelImportException(String message, ExcelImportEnum type) { + super(message); + this.type = type; + } + + public ExcelImportException(ExcelImportEnum type, Throwable cause) { + super(type.getMsg(), cause); + } + + public ExcelImportEnum getType() { + return type; + } + + public void setType(ExcelImportEnum type) { + this.type = type; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelExportEnum.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelExportEnum.java new file mode 100644 index 0000000..c8d6687 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelExportEnum.java @@ -0,0 +1,26 @@ +package org.jeecgframework.poi.exception.excel.enums; +/** + * 导出异常类型枚举 + * @author JueYue + * @date 2014年6月19日 下午10:59:51 + */ +public enum ExcelExportEnum { + + PARAMETER_ERROR("Excel 导出 参数错误"), + EXPORT_ERROR("Excel导出错误"); + + private String msg; + + ExcelExportEnum(String msg){ + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelImportEnum.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelImportEnum.java new file mode 100644 index 0000000..6898bb1 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/excel/enums/ExcelImportEnum.java @@ -0,0 +1,25 @@ +package org.jeecgframework.poi.exception.excel.enums; +/** + * 导出异常类型枚举 + * @author JueYue + * @date 2014年6月19日 下午10:59:51 + */ +public enum ExcelImportEnum { + + GET_VALUE_ERROR("Excel 值获取失败"); + + private String msg; + + ExcelImportEnum(String msg){ + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/ExcelDataHandlerDefaultImpl.java b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/ExcelDataHandlerDefaultImpl.java new file mode 100644 index 0000000..1376803 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/ExcelDataHandlerDefaultImpl.java @@ -0,0 +1,36 @@ +package org.jeecgframework.poi.handler.impl; + +import org.jeecgframework.poi.handler.inter.IExcelDataHandler; + +/** + * 数据处理默认实现,返回空 + * + * @author JueYue + * @date 2014年6月20日 上午12:11:52 + */ +public abstract class ExcelDataHandlerDefaultImpl implements IExcelDataHandler { + /** + * 需要处理的字段 + */ + private String[] needHandlerFields; + + @Override + public Object exportHandler(Object obj, String name, Object value) { + return value; + } + + @Override + public Object importHandler(Object obj, String name, Object value) { + return value; + } + + @Override + public String[] getNeedHandlerFields() { + return needHandlerFields; + } + + public void setNeedHandlerFields(String[] needHandlerFields) { + this.needHandlerFields = needHandlerFields; + } + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/package-info.java b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/package-info.java new file mode 100644 index 0000000..a3df130 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/impl/package-info.java @@ -0,0 +1,6 @@ +/** + * 对接口的抽象的默认实现,避免用户实现过多方法 + * @author JueYue + * @date 2014年6月20日 上午12:09:27 + */ +package org.jeecgframework.poi.handler.impl; \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelDataHandler.java b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelDataHandler.java new file mode 100644 index 0000000..2901158 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelDataHandler.java @@ -0,0 +1,45 @@ +package org.jeecgframework.poi.handler.inter; + +/** + * Excel 导入导出 数据处理接口 + * + * @author JueYue + * @date 2014年6月19日 下午11:59:45 + */ +public interface IExcelDataHandler { + + /** + * 获取需要处理的字段,导入和导出统一处理了, + * 减少书写的字段 + * + * @return + */ + public String[] getNeedHandlerFields(); + + /** + * 导出处理方法 + * + * @param obj + * 当前对象 + * @param name + * 当前字段名称 + * @param value + * 当前值 + * @return + */ + public Object exportHandler(Object obj, String name, Object value); + + /** + * 导入处理方法 当前对象,当前字段名称,当前值 + * + * @param obj + * 当前对象 + * @param name + * 当前字段名称 + * @param value + * 当前值 + * @return + */ + public Object importHandler(Object obj, String name, Object value); + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelVerifyHandler.java b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelVerifyHandler.java new file mode 100644 index 0000000..bd46a6c --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/inter/IExcelVerifyHandler.java @@ -0,0 +1,24 @@ +package org.jeecgframework.poi.handler.inter; + +import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; +/** + * 导入校验接口 + * @author JueYue + * @date 2014年6月23日 下午11:08:21 + */ +public interface IExcelVerifyHandler { + /** + * 导出处理方法 + * + * @param obj + * 当前对象 + * @param name + * 当前字段名称 + * @param value + * 当前值 + * @return + */ + public ExcelVerifyHanlderResult verifyHandler(Object obj, String name, + Object value); + +} diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/handler/package-info.java b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/package-info.java new file mode 100644 index 0000000..6969c0a --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/handler/package-info.java @@ -0,0 +1,6 @@ +/** + * 数据处理中心,对导入导出进行数据处理 + * @author JueYue + * @date 2014年6月20日 上午12:08:09 + */ +package org.jeecgframework.poi.handler; \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/package-info.java b/easypoi-base/src/main/java/org/jeecgframework/poi/package-info.java new file mode 100644 index 0000000..4b14b78 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/package-info.java @@ -0,0 +1,13 @@ +/** + * @author JueYue + * @date 2014年2月10日 + * @version 1.0 + * 对POI进行封装,通过注解的使用,完成POI的简易重复操作 + * 通过模板完成较为复杂的操作 + * 进阶步骤:
+ *

1.了解注解,图片类

+ *

2.模板语言

+ *

3.模板组合

+ * + */ +package org.jeecgframework.poi; \ No newline at end of file diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java new file mode 100644 index 0000000..2a34299 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java @@ -0,0 +1,294 @@ +package org.jeecgframework.poi.util; + +import org.apache.poi.POIXMLDocumentPart; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ss.usermodel.PictureData; +import org.apache.poi.xssf.usermodel.*; +import org.jeecgframework.poi.excel.annotation.Excel; +import org.jeecgframework.poi.excel.annotation.ExcelCollection; +import org.jeecgframework.poi.excel.annotation.ExcelEntity; +import org.jeecgframework.poi.excel.annotation.ExcelIgnore; +import org.jeecgframework.poi.excel.entity.vo.PoiBaseConstants; +import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +public class ExcelPublicUtil { + + public static String getWebRootPath(String filePath) { + // 这个path还是要测试的 + String path = ExcelPublicUtil.class.getClassLoader().getResource("") + .getPath() + + filePath; + path = path.replace("WEB-INF/classes/", ""); + path = path.replace("file:/", ""); + return path; + } + + /** + * 获取class的 包括父类的 + * + * @param clazz + * @return + */ + public static Field[] getClassFields(Class clazz) { + List list = new ArrayList(); + Field[] fields; + do { + fields = clazz.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + list.add(fields[i]); + } + clazz = clazz.getSuperclass(); + } while (clazz != Object.class && clazz != null); + return list.toArray(fields); + } + + /** + * 判断是不是集合的实现类 + * + * @param clazz + * @return + */ + public static boolean isCollection(Class clazz) { + return Collection.class.isAssignableFrom(clazz); + } + + /** + * 判断是否不要在这个excel操作中 + * + * @param + * @param field + * @param targetId + * @return + */ + public static boolean isNotUserExcelUserThis(List exclusionsList, + Field field, String targetId) { + boolean boo = true; + if (field.getAnnotation(ExcelIgnore.class) != null) { + boo = true; + } else if (boo + && field.getAnnotation(ExcelCollection.class) != null + && isUseInThis(field.getAnnotation(ExcelCollection.class) + .name(), targetId) + && (exclusionsList == null || !exclusionsList.contains(field + .getAnnotation(ExcelCollection.class).name()))) { + boo = false; + } else if (boo + && field.getAnnotation(Excel.class) != null + && isUseInThis(field.getAnnotation(Excel.class).name(), + targetId) + && (exclusionsList == null || !exclusionsList.contains(field + .getAnnotation(Excel.class).name()))) { + boo = false; + } else if (boo + && field.getAnnotation(ExcelEntity.class) != null + && isUseInThis(field.getAnnotation(ExcelEntity.class).name(), + targetId) + && (exclusionsList == null || !exclusionsList.contains(field + .getAnnotation(ExcelEntity.class).name()))) { + boo = false; + } + return boo; + } + + /** + * 判断是不是使用 + * + * @param exportName + * @param targetId + * @return + */ + private static boolean isUseInThis(String exportName, String targetId) { + return targetId == null || exportName.equals("") + || exportName.indexOf("_") < 0 + || exportName.indexOf(targetId) != -1; + } + + /** + * 是不是java基础类 + * + * @param field + * @return + */ + public static boolean isJavaClass(Field field) { + Class fieldType = field.getType(); + boolean isBaseClass = false; + if (fieldType.isArray()) { + isBaseClass = false; + } else if (fieldType.isPrimitive() || fieldType.getPackage() == null + || fieldType.getPackage().getName().equals("java.lang") + || fieldType.getPackage().getName().equals("java.math") + || fieldType.getPackage().getName().equals("java.util")) { + isBaseClass = true; + } + return isBaseClass; + } + + /** + * 彻底创建一个对象 + * + * @param clazz + * @return + */ + public static Object createObject(Class clazz, String targetId) { + Object obj = null; + Method setMethod; + try { + obj = clazz.newInstance(); + Field[] fields = getClassFields(clazz); + for (Field field : fields) { + if (isNotUserExcelUserThis(null, field, targetId)) { + continue; + } + if (isCollection(field.getType())) { + ExcelCollection collection = field + .getAnnotation(ExcelCollection.class); + setMethod = getMethod(field.getName(), clazz, + field.getType()); + setMethod.invoke(obj, collection.type().newInstance()); + } else if (!isJavaClass(field)) { + setMethod = getMethod(field.getName(), clazz, + field.getType()); + setMethod.invoke(obj, + createObject(field.getType(), targetId)); + } + } + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("创建对象异常"); + } + return obj; + + } + + /** + * 获取GET方法 + * + * @param name + * @param pojoClass + * @return + * @throws Exception + */ + public static Method getMethod(String name, Class pojoClass) + throws Exception { + StringBuffer getMethodName = new StringBuffer(PoiBaseConstants.GET); + getMethodName.append(name.substring(0, 1).toUpperCase()); + getMethodName.append(name.substring(1)); + Method method = null; + try { + method = pojoClass.getMethod(getMethodName.toString(), + new Class[] {}); + } catch (Exception e) { + method = pojoClass.getMethod( + getMethodName.toString().replace(PoiBaseConstants.GET, + PoiBaseConstants.IS), new Class[] {}); + } + return method; + } + + /** + * 获取SET方法 + * + * @param name + * @param pojoClass + * @param type + * @return + * @throws Exception + */ + public static Method getMethod(String name, Class pojoClass, + Class type) throws Exception { + StringBuffer getMethodName = new StringBuffer(PoiBaseConstants.SET); + getMethodName.append(name.substring(0, 1).toUpperCase()); + getMethodName.append(name.substring(1)); + return pojoClass.getMethod(getMethodName.toString(), + new Class[] { type }); + } + + /** + * @param photoByte + * @return + */ + public static String getFileExtendName(byte[] photoByte) { + String strFileExtendName = "JPG"; + if ((photoByte[0] == 71) && (photoByte[1] == 73) + && (photoByte[2] == 70) && (photoByte[3] == 56) + && ((photoByte[4] == 55) || (photoByte[4] == 57)) + && (photoByte[5] == 97)) { + strFileExtendName = "GIF"; + } else if ((photoByte[6] == 74) && (photoByte[7] == 70) + && (photoByte[8] == 73) && (photoByte[9] == 70)) { + strFileExtendName = "JPG"; + } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) { + strFileExtendName = "BMP"; + } else if ((photoByte[1] == 80) && (photoByte[2] == 78) + && (photoByte[3] == 71)) { + strFileExtendName = "PNG"; + } + return strFileExtendName; + } + + /** + * 获取Excel2003图片 + * + * @param sheet + * 当前sheet对象 + * @param workbook + * 工作簿对象 + * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData + */ + public static Map getSheetPictrues03(HSSFSheet sheet, + HSSFWorkbook workbook) { + Map sheetIndexPicMap = new HashMap(); + List pictures = workbook.getAllPictures(); + if (pictures.size() != 0) { + for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { + HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor(); + if (shape instanceof HSSFPicture) { + HSSFPicture pic = (HSSFPicture) shape; + int pictureIndex = pic.getPictureIndex() - 1; + HSSFPictureData picData = pictures.get(pictureIndex); + String picIndex = String.valueOf(anchor.getRow1()) + "_" + + String.valueOf(anchor.getCol1()); + sheetIndexPicMap.put(picIndex, picData); + } + } + return sheetIndexPicMap; + } else { + return null; + } + } + + /** + * 获取Excel2007图片 + * + * @param sheet + * 当前sheet对象 + * @param workbook + * 工作簿对象 + * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData + */ + public static Map getSheetPictrues07(XSSFSheet sheet, + XSSFWorkbook workbook) { + Map sheetIndexPicMap = new HashMap(); + for (POIXMLDocumentPart dr : sheet.getRelations()) { + if (dr instanceof XSSFDrawing) { + XSSFDrawing drawing = (XSSFDrawing) dr; + List shapes = drawing.getShapes(); + for (XSSFShape shape : shapes) { + XSSFPicture pic = (XSSFPicture) shape; + XSSFClientAnchor anchor = pic.getPreferredSize(); + CTMarker ctMarker = anchor.getFrom(); + String picIndex = ctMarker.getRow() + "_" + + ctMarker.getCol(); + sheetIndexPicMap.put(picIndex, pic.getPictureData()); + } + } + } + return sheetIndexPicMap; + } + +} diff --git a/easypoi-base/target/classes/META-INF/MANIFEST.MF b/easypoi-base/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..77ec9a5 --- /dev/null +++ b/easypoi-base/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: jue +Build-Jdk: 1.6.0_32 +Created-By: Maven Integration for Eclipse + diff --git a/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties new file mode 100644 index 0000000..df9d688 --- /dev/null +++ b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Thu Jul 24 22:26:27 CST 2014 +version=2.0.1 +groupId=org.jeecgframework +m2e.projectName=easypoi-base +m2e.projectLocation=D\:\\mySpace\\jeecg\\easypoi\\easypoi-base +artifactId=easypoi-base diff --git a/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.xml b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.xml new file mode 100644 index 0000000..3fb8ca9 --- /dev/null +++ b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-base + + + + org.apache.poi + poi + + + org.apache.poi + poi-ooxml + + + org.apache.poi + poi-ooxml-schemas + + + org.apache.poi + poi-scratchpad + + + + + com.google.guava + guava + + + + commons-lang + commons-lang + + + + + + org.slf4j + slf4j-api + + + \ No newline at end of file diff --git a/easypoi-base/target/maven-archiver/pom.properties b/easypoi-base/target/maven-archiver/pom.properties new file mode 100644 index 0000000..74f2bec --- /dev/null +++ b/easypoi-base/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Wed Jun 25 10:09:32 CST 2014 +version=2.0.1 +groupId=org.jeecgframework +artifactId=easypoi-base diff --git a/easypoi-test/.classpath b/easypoi-test/.classpath new file mode 100644 index 0000000..13ed0c0 --- /dev/null +++ b/easypoi-test/.classpath @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/easypoi-test/.project b/easypoi-test/.project new file mode 100644 index 0000000..8305fe2 --- /dev/null +++ b/easypoi-test/.project @@ -0,0 +1,23 @@ + + + easypoi-test + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/easypoi-test/.settings/org.eclipse.core.resources.prefs b/easypoi-test/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..1f887b6 --- /dev/null +++ b/easypoi-test/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 diff --git a/easypoi-test/.settings/org.eclipse.jdt.core.prefs b/easypoi-test/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..14f521d --- /dev/null +++ b/easypoi-test/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/easypoi-test/.settings/org.eclipse.m2e.core.prefs b/easypoi-test/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..14b697b --- /dev/null +++ b/easypoi-test/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/easypoi-test/pom.xml b/easypoi-test/pom.xml new file mode 100644 index 0000000..5b81709 --- /dev/null +++ b/easypoi-test/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-test + + + org.jeecgframework + easypoi-base + + + + org.slf4j + slf4j-log4j12 + + + + junit + junit + + + \ No newline at end of file diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/CourseEntity.java b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/CourseEntity.java new file mode 100644 index 0000000..92e9a97 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/CourseEntity.java @@ -0,0 +1,108 @@ +package org.jeecgframework.poi.entity; + +import java.util.List; + +import org.jeecgframework.poi.excel.annotation.Excel; +import org.jeecgframework.poi.excel.annotation.ExcelCollection; +import org.jeecgframework.poi.excel.annotation.ExcelEntity; +import org.jeecgframework.poi.excel.annotation.ExcelTarget; +import org.jeecgframework.poi.excel.annotation.ExcelVerify; + +/** + * @Title: Entity + * @Description: 课程 + * @author jueyue + * @date 2013-08-31 22:53:07 + * @version V1.0 + * + */ +@SuppressWarnings("serial") +@ExcelTarget("courseEntity") +public class CourseEntity implements java.io.Serializable { + /** 主键 */ + private String id; + /** 课程名称 */ + @Excel(name = "课程名称", orderNum = "1", needMerge = true) + private String name; + /** 老师主键 */ + @ExcelEntity(id = "yuwen") + @ExcelVerify() + private TeacherEntity teacher; + /** 老师主键 */ + @ExcelEntity(id = "shuxue") + private TeacherEntity shuxueteacher; + + @ExcelCollection(name = "选课学生", orderNum = "4") + private List students; + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 主键 + */ + + public String getId() { + return this.id; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 主键 + */ + public void setId(String id) { + this.id = id; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 课程名称 + */ + public String getName() { + return this.name; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 课程名称 + */ + public void setName(String name) { + this.name = name; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 老师主键 + */ + public TeacherEntity getTeacher() { + return teacher; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 老师主键 + */ + public void setTeacher(TeacherEntity teacher) { + this.teacher = teacher; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } + + public TeacherEntity getShuxueteacher() { + return shuxueteacher; + } + + public void setShuxueteacher(TeacherEntity shuxueteacher) { + this.shuxueteacher = shuxueteacher; + } +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/StudentEntity.java b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/StudentEntity.java new file mode 100644 index 0000000..b8667d4 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/StudentEntity.java @@ -0,0 +1,107 @@ +package org.jeecgframework.poi.entity; + +import org.jeecgframework.poi.excel.annotation.Excel; + +import java.util.Date; + +/** + * @author jueyue + * @version V1.0 + * @Title: Entity + * @Description: 学生 + * @date 2013-08-31 22:53:34 + */ +@SuppressWarnings("serial") +public class StudentEntity implements java.io.Serializable { + /** + * id + */ + private String id; + /** + * 学生姓名 + */ + @Excel(name = "学生姓名", height = 20 ,width = 30) + private String name; + /** + * 学生性别 + */ + @Excel(name = "学生性别", replace = {"男_1","女_2"}) + private int sex; + + @Excel(name = "出生日期", format = "yyyy-MM-dd HH:mm:ss", mergeVertical = true) + private Date birthday; + /** + * 课程主键 + */ + private CourseEntity course; + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String id + */ + public String getId() { + return this.id; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String id + */ + public void setId(String id) { + this.id = id; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 学生姓名 + */ + public String getName() { + return this.name; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 学生姓名 + */ + public void setName(String name) { + this.name = name; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 学生性别 + */ + public int getSex() { + return this.sex; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 学生性别 + */ + public void setSex(int sex) { + this.sex = sex; + } + + public CourseEntity getCourse() { + return course; + } + + public void setCourse(CourseEntity course) { + this.course = course; + } + + public Date getBirthday() { + return birthday; + } + + public void setBirthday(Date birthday) { + this.birthday = birthday; + } +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/TeacherEntity.java b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/TeacherEntity.java new file mode 100644 index 0000000..58613ed --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/TeacherEntity.java @@ -0,0 +1,72 @@ +package org.jeecgframework.poi.entity; + +import org.jeecgframework.poi.excel.annotation.Excel; +import org.jeecgframework.poi.excel.annotation.ExcelTarget; + +/** + * @Title: Entity + * @Description: 课程老师 + * @author jueyue + * @date 2013-08-31 22:52:17 + * @version V1.0 + * + */ +@SuppressWarnings("serial") +@ExcelTarget("teacherEntity") +public class TeacherEntity implements java.io.Serializable { + /** id */ + @Excel(name = "老师ID_teacherEntity,老师属性_courseEntity", orderNum = "2", needMerge = false) + private String id; + /** name */ + @Excel(name = "语文老师_yuwen,数学老师_shuxue", orderNum = "2", needMerge = true) + private String name; + + /* + * @Excel(exportName="老师照片",orderNum="3",exportType=2,exportFieldHeight=15, + * exportFieldWidth=20) private String pic; + */ + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String id + */ + + public String getId() { + return this.id; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String id + */ + public void setId(String id) { + this.id = id; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String name + */ + public String getName() { + return this.name; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String name + */ + public void setName(String name) { + this.name = name; + } + + /* + * public String getPic() { // if(StringUtils.isEmpty(pic)){ // pic = + * "plug-in/login/images/jeecg.png"; // } return pic; } + * + * public void setPic(String pic) { this.pic = pic; } + */ +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtilTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtilTest.java new file mode 100644 index 0000000..8a6cf76 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtilTest.java @@ -0,0 +1,28 @@ +package org.jeecgframework.poi.excel; + +import static org.junit.Assert.*; + +import java.io.File; +import java.util.Collection; +import java.util.List; + +import org.jeecgframework.poi.entity.CourseEntity; +import org.jeecgframework.poi.entity.StudentEntity; +import org.jeecgframework.poi.excel.entity.ImportParams; +import org.junit.Test; + +public class ExcelImportUtilTest { + + @Test + public void test() { + ImportParams params = new ImportParams(); + params.setTitleRows(2); + params.setHeadRows(2); + List list = ExcelImportUtil.importExcel(new File( + "d:/tt.xls"), CourseEntity.class, params); + for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i).getName()); + } + } + +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/MyExcelExport.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/MyExcelExport.java new file mode 100644 index 0000000..7665fe0 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/MyExcelExport.java @@ -0,0 +1,43 @@ +package org.jeecgframework.poi.excel; + +import java.util.Map; + +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.CellStyle; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.export.ExcelExportServer; + +public class MyExcelExport extends ExcelExportServer { + + @Override + public HSSFCellStyle getTitleStyle(HSSFWorkbook workbook, + ExportParams entity) { + return super.getTitleStyle(workbook, entity); + } + + @Override + public HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook, + ExportParams entity) { + return super.getHeaderStyle(workbook, entity); + } + + @Override + public HSSFCellStyle getTwoStyle(HSSFWorkbook workbook, boolean isWarp) { + return super.getTwoStyle(workbook, isWarp); + } + + @Override + public HSSFCellStyle getOneStyle(HSSFWorkbook workbook, boolean isWarp) { + return super.getOneStyle(workbook, isWarp); + } + + @Override + public CellStyle getStyles(Map map, boolean needOne, + boolean isWrap) { + return super.getStyles(map, needOne, isWrap); + } + + + +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/CourseHanlder.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/CourseHanlder.java new file mode 100644 index 0000000..0a5d96b --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/CourseHanlder.java @@ -0,0 +1,22 @@ +package org.jeecgframework.poi.excel.test; + +import org.jeecgframework.poi.handler.impl.ExcelDataHandlerDefaultImpl; + +public class CourseHanlder extends ExcelDataHandlerDefaultImpl { + + @Override + public Object exportHandler(Object obj, String name, Object value) { + if(name.equals("课程名称")){ + return String.valueOf(value)+"课程"; + } + return super.exportHandler(obj, name, value); + } + + @Override + public Object importHandler(Object obj, String name, Object value) { + return super.importHandler(obj, name, value); + } + + + +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilDataHandlerTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilDataHandlerTest.java new file mode 100644 index 0000000..de1da89 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilDataHandlerTest.java @@ -0,0 +1,73 @@ +package org.jeecgframework.poi.excel.test; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.jeecgframework.poi.entity.CourseEntity; +import org.jeecgframework.poi.entity.StudentEntity; +import org.jeecgframework.poi.entity.TeacherEntity; +import org.jeecgframework.poi.excel.ExcelExportUtil; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * 数据处理测试 Created by jue on 14-4-19. + */ +public class ExcelExportUtilDataHandlerTest { + + List list = new ArrayList(); + CourseEntity courseEntity; + + @Before + public void testBefore() { + courseEntity = new CourseEntity(); + courseEntity.setId("1131"); + courseEntity.setName("小白"); + + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); + + teacherEntity = new TeacherEntity(); + teacherEntity.setId("121312314312421131"); + teacherEntity.setName("老王"); + courseEntity.setShuxueteacher(teacherEntity); + + StudentEntity studentEntity = new StudentEntity(); + studentEntity.setId("11231"); + studentEntity.setName("撒旦法司法局"); + studentEntity.setBirthday(new Date()); + studentEntity.setSex(1); + List studentList = new ArrayList(); + studentList.add(studentEntity); + studentList.add(studentEntity); + courseEntity.setStudents(studentList); + + for (int i = 0; i < 3; i++) { + list.add(courseEntity); + } + } + + /** + * 基本导出测试 + * + * @throws Exception + */ + @Test + public void testExportExcel() throws Exception { + ExportParams exportParams = new ExportParams("2412312", "测试", "测试"); + CourseHanlder hanlder = new CourseHanlder(); + hanlder.setNeedHandlerFields(new String[]{"课程名称"}); + exportParams.setDataHanlder(hanlder); + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(exportParams, + CourseEntity.class, list); + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilIdTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilIdTest.java new file mode 100644 index 0000000..c44b276 --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilIdTest.java @@ -0,0 +1,78 @@ +package org.jeecgframework.poi.excel.test; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.jeecgframework.poi.entity.CourseEntity; +import org.jeecgframework.poi.entity.StudentEntity; +import org.jeecgframework.poi.entity.TeacherEntity; +import org.jeecgframework.poi.excel.ExcelExportUtil; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.junit.Before; +import org.junit.Test; + +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * 关系导出测试 Created by JueYue on 14-4-19. + */ +public class ExcelExportUtilIdTest { + + List list = new ArrayList(); + List telist = new ArrayList(); + CourseEntity courseEntity; + + @Before + public void testBefore() { + courseEntity = new CourseEntity(); + courseEntity.setId("1131"); + courseEntity.setName("小白"); + + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); + + StudentEntity studentEntity = new StudentEntity(); + studentEntity.setId("11231"); + studentEntity.setName("撒旦法司法局"); + studentEntity.setBirthday(new Date()); + studentEntity.setSex(1); + List studentList = new ArrayList(); + studentList.add(studentEntity); + studentList.add(studentEntity); + courseEntity.setStudents(studentList); + + for (int i = 0; i < 3; i++) { + list.add(courseEntity); + } + } + + @Before + public void testBefor2() { + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12132131231231231"); + teacherEntity.setName("你们"); + + for (int i = 0; i < 3; i++) { + telist.add(teacherEntity); + } + } + + + /** + * 单行表头导出测试 + * + * @throws Exception + */ + @Test + public void testExportExcel() throws Exception { + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams( + "2412312", "测试", "测试"), TeacherEntity.class, telist); + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } + +} diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilTest.java new file mode 100644 index 0000000..17a99ee --- /dev/null +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportUtilTest.java @@ -0,0 +1,144 @@ +package org.jeecgframework.poi.excel.test; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Workbook; +import org.jeecgframework.poi.entity.CourseEntity; +import org.jeecgframework.poi.entity.StudentEntity; +import org.jeecgframework.poi.entity.TeacherEntity; +import org.jeecgframework.poi.excel.ExcelExportUtil; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.TemplateExportParams; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +/** + * Created by jue on 14-4-19. + */ +public class ExcelExportUtilTest { + + List list = new ArrayList(); + CourseEntity courseEntity; + + @Before + public void testBefore() { + courseEntity = new CourseEntity(); + courseEntity.setId("1131"); + courseEntity.setName("小白"); + + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); + + teacherEntity = new TeacherEntity(); + teacherEntity.setId("121312314312421131"); + teacherEntity.setName("老王"); + courseEntity.setShuxueteacher(teacherEntity); + + StudentEntity studentEntity = new StudentEntity(); + studentEntity.setId("11231"); + studentEntity.setName("撒旦法司法局"); + studentEntity.setBirthday(new Date()); + studentEntity.setSex(1); + List studentList = new ArrayList(); + studentList.add(studentEntity); + studentList.add(studentEntity); + courseEntity.setStudents(studentList); + + for (int i = 0; i < 3; i++) { + list.add(courseEntity); + } + } + + /** + * 基本导出测试 + * + * @throws Exception + */ + @Test + public void testExportExcel() throws Exception { + Date start = new Date(); + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams( + "2412312", "测试", "测试"), CourseEntity.class, list); + System.out.println(new Date().getTime() - start.getTime()); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } + /** + * 单行表头测试 + * + * @throws Exception + */ + //@Test + public void testExportTitleExcel() throws Exception { + Date start = new Date(); + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams( + "2412312","测试"), CourseEntity.class, list); + System.out.println(new Date().getTime() - start.getTime()); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } + + /** + * 模板导出测试 + * + * @throws Exception + */ + //@Test + public void testTempExportExcel() throws Exception { + TemplateExportParams params = new TemplateExportParams(); + params.setHeadingRows(2); + params.setHeadingStartRow(2); + params.setTemplateUrl("tt.xls"); + Workbook book = ExcelExportUtil.exportExcel(params, CourseEntity.class, list, + new HashMap()); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/t_tt.xls"); + book.write(fos); + fos.close(); + } + + /** + * 25W行导出测试 + * + * @throws Exception + */ + //@Test + public void oneHundredThousandRowTest() throws Exception { + for (int i = 0; i < 250000; i++) { + list.add(courseEntity); + } + Date start = new Date(); + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams( + "2412312", "测试", "测试"), CourseEntity.class, list); + System.out.println(new Date().getTime() - start.getTime()); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } + +} diff --git a/easypoi-test/target/classes/META-INF/MANIFEST.MF b/easypoi-test/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..77ec9a5 --- /dev/null +++ b/easypoi-test/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: jue +Build-Jdk: 1.6.0_32 +Created-By: Maven Integration for Eclipse + diff --git a/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.properties b/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.properties new file mode 100644 index 0000000..9f1361d --- /dev/null +++ b/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Thu Jul 24 22:26:28 CST 2014 +version=2.0.1 +groupId=org.jeecgframework +m2e.projectName=easypoi-test +m2e.projectLocation=D\:\\mySpace\\jeecg\\easypoi\\easypoi-test +artifactId=easypoi-test diff --git a/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.xml b/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.xml new file mode 100644 index 0000000..5b81709 --- /dev/null +++ b/easypoi-test/target/classes/META-INF/maven/org.jeecgframework/easypoi-test/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-test + + + org.jeecgframework + easypoi-base + + + + org.slf4j + slf4j-log4j12 + + + + junit + junit + + + \ No newline at end of file diff --git a/easypoi-web/.classpath b/easypoi-web/.classpath new file mode 100644 index 0000000..f67a1d3 --- /dev/null +++ b/easypoi-web/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/easypoi-web/.project b/easypoi-web/.project new file mode 100644 index 0000000..2197815 --- /dev/null +++ b/easypoi-web/.project @@ -0,0 +1,23 @@ + + + easypoi-web + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/easypoi-web/.settings/org.eclipse.core.resources.prefs b/easypoi-web/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..1f887b6 --- /dev/null +++ b/easypoi-web/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 diff --git a/easypoi-web/.settings/org.eclipse.jdt.core.prefs b/easypoi-web/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..14f521d --- /dev/null +++ b/easypoi-web/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,5 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/easypoi-web/.settings/org.eclipse.m2e.core.prefs b/easypoi-web/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..14b697b --- /dev/null +++ b/easypoi-web/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/easypoi-web/pom.xml b/easypoi-web/pom.xml new file mode 100644 index 0000000..09ec6d2 --- /dev/null +++ b/easypoi-web/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-web + + + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-core + + + + javax.servlet + servlet-api + provided + + + + org.jeecgframework + easypoi-base + + + \ No newline at end of file diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/BasePOIConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/BasePOIConstants.java new file mode 100644 index 0000000..b351701 --- /dev/null +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/BasePOIConstants.java @@ -0,0 +1,22 @@ +package org.jeecgframework.poi.excel.entity.vo; +/** + * 基础POI常量 + * @author JueYue + * @date 2014年6月30日 下午9:23:37 + */ +interface BasePOIConstants { + + /** + * 注解对象 + */ + public final static String CLASS = "entity"; + /** + *表格参数 + */ + public final static String PARAMS = "params"; + /** + *下载文件名称 + */ + public final static String FILE_NAME = "fileName"; + +} diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalPOIConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalPOIConstants.java new file mode 100644 index 0000000..036e640 --- /dev/null +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalPOIConstants.java @@ -0,0 +1,22 @@ +package org.jeecgframework.poi.excel.entity.vo; + +/** + * 正常导出Excel + * @Author JueYue on 14-3-8. + * 静态常量 + */ +public interface NormalPOIConstants extends BasePOIConstants { + /** + * 单Sheet导出 + */ + public final static String JEECG_EXCEL_VIEW = "jeecgExcelView"; + /** + * 数据列表 + */ + public final static String DATA_LIST = "data"; + /** + * 多Sheet 对象 + */ + public final static String MAP_LIST = "mapList"; + +} diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplatePOIConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplatePOIConstants.java new file mode 100644 index 0000000..548b7da --- /dev/null +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplatePOIConstants.java @@ -0,0 +1,21 @@ +package org.jeecgframework.poi.excel.entity.vo; +/** + * 模板Excel导出常量 + * @author JueYue + * @date 2014年6月30日 下午9:26:52 + */ +public interface TemplatePOIConstants extends BasePOIConstants { + /** + * 模板导出 + */ + public final static String JEECG_TEMPLATE_EXCEL_VIEW = "jeecgTemplateExcelView"; + /** + * 数据列表 + */ + public final static String LIST_DATA = "list"; + /** + * 模板参数 + */ + public final static String MAP_DATA = "map"; + +} diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgSingleExcelView.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgSingleExcelView.java new file mode 100644 index 0000000..667b5a4 --- /dev/null +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgSingleExcelView.java @@ -0,0 +1,50 @@ +package org.jeecgframework.poi.excel.view; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.vo.NormalPOIConstants; +import org.jeecgframework.poi.excel.export.ExcelExportServer; +import org.springframework.web.servlet.view.document.AbstractExcelView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +/** + * @Author JueYue on 14-3-8. Excel 生成解析器,减少用户操作 + */ +@SuppressWarnings("unchecked") +public class JeecgSingleExcelView extends AbstractExcelView { + + @Override + protected void buildExcelDocument(Map model, + HSSFWorkbook hssfWorkbook, HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse) throws Exception { + String codedFileName = "临时文件.xls"; + if (model.containsKey(NormalPOIConstants.FILE_NAME)) { + codedFileName = (String) model.get(NormalPOIConstants.FILE_NAME) + + ".xls"; + } + httpServletResponse.setHeader("content-disposition", + "attachment;filename=" + + new String(codedFileName.getBytes(), "iso8859-1")); + if (model.containsKey(NormalPOIConstants.MAP_LIST)) { + List> list = (List>) model + .get(NormalPOIConstants.MAP_LIST); + for (Map map : list) { + new ExcelExportServer().createSheet(hssfWorkbook, + (ExportParams) map.get(NormalPOIConstants.PARAMS), + (Class) map.get(NormalPOIConstants.CLASS), + (Collection) map.get(NormalPOIConstants.DATA_LIST)); + } + } else { + new ExcelExportServer().createSheet(hssfWorkbook, + (ExportParams) model.get(NormalPOIConstants.PARAMS), + (Class) model.get(NormalPOIConstants.CLASS), + (Collection) model.get(NormalPOIConstants.DATA_LIST)); + } + } +} diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateExcelView.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateExcelView.java new file mode 100644 index 0000000..0e60006 --- /dev/null +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateExcelView.java @@ -0,0 +1,52 @@ +package org.jeecgframework.poi.excel.view; + +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.poi.ss.usermodel.Workbook; +import org.jeecgframework.poi.excel.ExcelExportUtil; +import org.jeecgframework.poi.excel.entity.TemplateExportParams; +import org.jeecgframework.poi.excel.entity.vo.NormalPOIConstants; +import org.jeecgframework.poi.excel.entity.vo.TemplatePOIConstants; +import org.springframework.web.servlet.view.AbstractView; + +/** + * 模板视图 + * + * @author JueYue + * @date 2014年6月30日 下午9:15:49 + */ +@SuppressWarnings("unchecked") +public class JeecgTemplateExcelView extends AbstractView { + + private static final String CONTENT_TYPE = "application/vnd.ms-excel"; + + public JeecgTemplateExcelView() { + setContentType(CONTENT_TYPE); + } + + @Override + protected void renderMergedOutputModel(Map model, + HttpServletRequest request, HttpServletResponse response) + throws Exception { + String codedFileName = "临时文件.xls"; + if (model.containsKey(NormalPOIConstants.FILE_NAME)) { + codedFileName = (String) model.get(NormalPOIConstants.FILE_NAME) + + ".xls"; + } + response.setHeader("content-disposition", "attachment;filename=" + + new String(codedFileName.getBytes(), "iso8859-1")); + Workbook workbook = ExcelExportUtil.exportExcel( + (TemplateExportParams)model.get(TemplatePOIConstants.PARAMS), + (Class) model.get(TemplatePOIConstants.CLASS), + (List)model.get(TemplatePOIConstants.LIST_DATA), + (Map)model.get(TemplatePOIConstants.MAP_DATA)); + ServletOutputStream out = response.getOutputStream(); + workbook.write(out); + out.flush(); + } +} diff --git a/easypoi-web/target/classes/META-INF/MANIFEST.MF b/easypoi-web/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..77ec9a5 --- /dev/null +++ b/easypoi-web/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Built-By: jue +Build-Jdk: 1.6.0_32 +Created-By: Maven Integration for Eclipse + diff --git a/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.properties b/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.properties new file mode 100644 index 0000000..0edcb2a --- /dev/null +++ b/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Thu Jul 24 22:26:28 CST 2014 +version=2.0.1 +groupId=org.jeecgframework +m2e.projectName=easypoi-web +m2e.projectLocation=D\:\\mySpace\\jeecg\\easypoi\\easypoi-web +artifactId=easypoi-web diff --git a/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.xml b/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.xml new file mode 100644 index 0000000..09ec6d2 --- /dev/null +++ b/easypoi-web/target/classes/META-INF/maven/org.jeecgframework/easypoi-web/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + + org.jeecgframework + easypoi + 2.0.1 + + easypoi-web + + + + + org.springframework + spring-web + + + org.springframework + spring-webmvc + + + org.springframework + spring-core + + + + javax.servlet + servlet-api + provided + + + + org.jeecgframework + easypoi-base + + + \ No newline at end of file diff --git a/easypoi-web/target/maven-archiver/pom.properties b/easypoi-web/target/maven-archiver/pom.properties new file mode 100644 index 0000000..130815f --- /dev/null +++ b/easypoi-web/target/maven-archiver/pom.properties @@ -0,0 +1,5 @@ +#Generated by Maven +#Wed Jun 25 10:09:34 CST 2014 +version=2.0.1 +groupId=org.jeecgframework +artifactId=easypoi-web diff --git a/package.bat b/package.bat new file mode 100644 index 0000000..84e3f30 --- /dev/null +++ b/package.bat @@ -0,0 +1 @@ +cmd /k mvn package \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..c690dda --- /dev/null +++ b/pom.xml @@ -0,0 +1,156 @@ + + 4.0.0 + org.jeecgframework + easypoi + 2.0.1 + pom + easypoi + + easypoi-base + easypoi-web + easypoi-test + + + www.jeecg.org + office 工具类 基于 poi + + + + JueYue + qrb.jueyue@gmail.com + + + + + 3.9 + 3.9 + 3.9 + 3.9 + 16.0.1 + 1.09 + 2.6 + 1.6.1 + 3.1.1.RELEASE + 4.7 + + + + + + org.apache.poi + poi + ${poi.version} + + + org.apache.poi + poi-ooxml + ${poi-ooxml.version} + + + org.apache.poi + poi-ooxml-schemas + ${poi-ooxml-schemas.version} + + + org.apache.poi + poi-scratchpad + ${poi-scratchpad.version} + + + + + com.google.guava + guava + ${guava.version} + + + + commons-lang + commons-lang + ${commons-lang.version} + + + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.slf4j + slf4j-log4j12 + ${slf4j.version} + provided + + + + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework + spring-core + ${spring.version} + + + + javax.servlet + servlet-api + 2.5 + provided + + + + + junit + junit + ${junit.version} + test + + + + + org.jeecgframework + easypoi-base + 2.0.1 + + + + + + + postaop-pay-platform-release + http://192.168.0.99:8081/nexus/content/repositories/postaop-common-release/ + + + postaop-pay-platform-snapshot + http://192.168.0.99:8081/nexus/content/repositoriespostaop-common-snapshot/ + + + + + + + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + true + UTF-8 + + + + + + \ No newline at end of file