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 index 81d5cee..e53554e 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/ExcelCache.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/ExcelCache.java @@ -17,30 +17,30 @@ import org.jeecgframework.poi.cache.manager.POICacheManager; */ 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; - } + 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/WordCache.java b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/WordCache.java index f5ce5a6..7fcf72d 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/cache/WordCache.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/WordCache.java @@ -14,22 +14,22 @@ import org.jeecgframework.poi.word.entity.JeecgXWPFDocument; */ public class WordCache { - public static JeecgXWPFDocument getXWPFDocumen(String url) { - InputStream is = null; - try { - is = POICacheManager.getFile(url); - JeecgXWPFDocument doc = new JeecgXWPFDocument(is); - return doc; - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return null; - } + public static JeecgXWPFDocument getXWPFDocumen(String url) { + InputStream is = null; + try { + is = POICacheManager.getFile(url); + JeecgXWPFDocument doc = new JeecgXWPFDocument(is); + return doc; + } catch (Exception 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 index efd378a..6392512 100644 --- 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 @@ -16,37 +16,39 @@ import org.slf4j.LoggerFactory; * @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 = POIPublicUtil.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; - } + private static final Logger logger = LoggerFactory.getLogger(FileLoade.class); + + public byte[] getFile(String url) { + FileInputStream fileis = null; + ByteArrayOutputStream baos = null; + try { + String path = POIPublicUtil.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 index 1a3d7fd..18b5fdb 100644 --- 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 @@ -19,27 +19,27 @@ import com.google.common.cache.LoadingCache; */ public final class POICacheManager { - private static LoadingCache loadingCache; + 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; - } + 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/excel/ExcelExportUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java index 24e3203..16599cc 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelExportUtil.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.usermodel.Workbook; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.TemplateExportParams; import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; @@ -21,88 +21,84 @@ import org.jeecgframework.poi.excel.export.template.ExcelExportOfTemplateUtil; */ 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 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 entity - * 表格标题属性 - * @param pojoClass - * Excel对象Class - * @param dataSet - * Excel对象数据List - */ - public static HSSFWorkbook exportExcel(ExportParams entity, - List entityList, Collection> dataSet) { - HSSFWorkbook workbook = new HSSFWorkbook(); - new ExcelExportServer().createSheetForMap(workbook, entity, entityList, dataSet); - return workbook; - } + /** + * @param entity + * 表格标题属性 + * @param pojoClass + * Excel对象Class + * @param dataSet + * Excel对象数据List + */ + public static HSSFWorkbook exportExcel(ExportParams entity, List entityList, + Collection> dataSet) { + HSSFWorkbook workbook = new HSSFWorkbook(); + new ExcelExportServer().createSheetForMap(workbook, entity, entityList, 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); - } + /** + * 一个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 params - * 导出参数类 - * @param map - * 模板集合 - * @return - */ - public static Workbook exportExcel(TemplateExportParams params, - Map map) { - return new ExcelExportOfTemplateUtil().createExcleByTemplate(params, - null, null, map); - } + /** + * 导出文件通过模板解析 + * + * @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 index ce57016..8702c82 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtil.java @@ -6,7 +6,6 @@ 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; @@ -18,95 +17,90 @@ import org.jeecgframework.poi.excel.imports.ExcelImportServer; * @date 2013-9-24 * @version 1.0 */ -@SuppressWarnings({ "hiding", "unchecked" }) +@SuppressWarnings({ "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 导入 数据源本地文件,不返回校验结果 导入 字 段类型 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 List importExcelByIs(InputStream inputstream, Class pojoClass, + ImportParams params) throws Exception { + return new ExcelImportServer().importExcelByIs(inputstream, pojoClass, params).getList(); + } - /** - * 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 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(); - } + /** + * 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; + } } 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 index 94e9212..8254e66 100644 --- 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 @@ -4,6 +4,7 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; + /** * Excel 导出基本注释 * @author JueYue @@ -12,90 +13,91 @@ import java.lang.annotation.Target; @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 ""; + /** + * cell 写入的设置的函数 + */ + public String cellFormula() default ""; + + /** + * 导出时间设置,如果字段是Date类型则不需要设置 数据库如果是string 类型,这个需要设置这个数据库格式 + */ + public String databaseFormat() default "yyyyMMddHHmmss"; + + /** + * 导出的时间格式,以这个是否为空来判断是否需要格式化日期 + */ + public String exportFormat() default ""; + + /** + * 时间格式,相当于同时设置了exportFormat 和 importFormat + */ + public String format() default ""; + + /** + * 导出时在excel中每个列的高度 单位为字符,一个汉字=2个字符 + */ + public int height() default 10; + + /** + * 导出类型 1 从file读取 2 是从数据库中读取 默认是文件 同样导入也是一样的 + */ + public int imageType() default 1; + + /** + * 导入的时间格式,以这个是否为空来判断是否需要格式化日期 + */ + public String importFormat() default ""; + + /** + * 是否换行 即支持\n + */ + public boolean isWrap() default true; + + /** + * 合并单元格依赖关系,比如第二列合并是基于第一列 则{1}就可以了 + */ + public int[] mergeRely() default {}; + + /** + * 纵向合并内容相同的单元格 + */ + public boolean mergeVertical() default false; + + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name(); + + /** + * 是否需要纵向合并单元格(用于含有list中,单个的单元格,合并list创建的多个row) + */ + public boolean needMerge() default false; + + /** + * 展示到第几个可以使用a_id,b_id来确定不同排序 + */ + public String orderNum() default "0"; + + /** + * 值得替换 导出是{a_id,b_id} 导入反过来,所以只用写一个 + */ + public String[] replace() default {}; + + /** + * 导入路径,如果是图片可以填写,默认是upload/className/ IconEntity这个类对应的就是upload/Icon/ + * + */ + public String savePath() default "upload"; + + /** + * 导出类型 1 是文本 2 是图片,3是函数 默认是文本 + */ + public int type() default 1; + + /** + * 导出时在excel中每个列的宽 单位为字符,一个汉字=2个字符 如 以列名列内容中较合适的长度 例如姓名列6 【姓名一般三个字】 + * 性别列4【男女占1,但是列标题两个汉字】 限制1-255 + */ + public int width() default 10; } 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 index c76961c..cd3e70b 100644 --- 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 @@ -15,25 +15,25 @@ import java.util.ArrayList; @Target(ElementType.FIELD) public @interface ExcelCollection { - /** - * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 - */ - public String id() default ""; + /** + * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 + */ + public String id() default ""; - /** - * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 - * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 - */ - public String name(); + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name(); - /** - * 展示到第几个同样可以使用a_id,b_id - * - */ - public String orderNum() default "0"; + /** + * 展示到第几个同样可以使用a_id,b_id + * + */ + public String orderNum() default "0"; - /** - * 创建时创建的类型 默认值是 arrayList - */ - public Class type() default ArrayList.class; + /** + * 创建时创建的类型 默认值是 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 index 88b9ed7..ae060ad 100644 --- 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 @@ -15,14 +15,14 @@ import java.lang.annotation.Target; @Target(ElementType.FIELD) public @interface ExcelEntity { - /** - * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 - */ - public String id() default ""; + /** + * 定义excel导出ID 来限定导出字段,处理一个类对应多个不同名称的情况 + */ + public String id() default ""; - /** - * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 - * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 - */ - public String name() default ""; + /** + * 导出时,对应数据库的字段 主要是用户区分每个字段, 不能有annocation重名的 导出时的列名 + * 导出排序跟定义了annotation的字段的顺序有关 可以使用a_id,b_id来确实是否使用 + */ + public String name() default ""; } 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 index 43ad7e1..3463980 100644 --- 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 @@ -14,8 +14,8 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface ExcelTarget { - /** - * 定义excel导出ID 来限定导出字段 - */ - public String value(); + /** + * 定义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 index 4c949ac..e1e7c04 100644 --- 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 @@ -7,64 +7,66 @@ package org.jeecgframework.poi.excel.annotation; * @date 2014年6月23日 下午10:46:26 */ public @interface ExcelVerify { - /** - * 接口校验 - * @return - */ - public boolean interHandler() default true; + /** + * 接口校验 + * @return + */ + public boolean interHandler() default true; - /** - * 不允许空 - * - * @return - */ - public boolean notNull() default false; + /** + * 是电子邮件 + * + * @return + */ + public boolean isEmail() default false; - /** - * 是13位移动电话 - * - * @return - */ - public boolean isMobile() default false; - /** - * 是座机号码 - * - * @return - */ - public boolean isTel() default false; + /** + * 是13位移动电话 + * + * @return + */ + public boolean isMobile() default false; - /** - * 是电子邮件 - * - * @return - */ - public boolean isEmail() default false; + /** + * 是座机号码 + * + * @return + */ + public boolean isTel() default false; - /** - * 最小长度 - * - * @return - */ - public int minLength() default -1; + /** + * 最大长度 + * + * @return + */ + public int maxLength() default -1; - /** - * 最大长度 - * - * @return - */ - public int maxLength() default -1; + /** + * 最小长度 + * + * @return + */ + public int minLength() default -1; - /** - * 正在表达式 - * - * @return - */ - public String regex() default ""; - /** - * 正在表达式,错误提示信息 - * - * @return - */ - public String regexTip() default "数据不符合规范"; + /** + * 不允许空 + * + * @return + */ + public boolean notNull() default false; + + /** + * 正在表达式 + * + * @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 index bc19f2f..5e1bf11 100644 --- 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 @@ -8,18 +8,17 @@ import org.jeecgframework.poi.handler.inter.IExcelDataHandler; * @date 2014年6月20日 下午1:56:52 */ public class ExcelBaseParams { - /** - * 数据处理接口,以此为主,replace,format都在这后面 - */ - private IExcelDataHandler dataHanlder; + /** + * 数据处理接口,以此为主,replace,format都在这后面 + */ + private IExcelDataHandler dataHanlder; - public IExcelDataHandler getDataHanlder() { - return dataHanlder; - } + public IExcelDataHandler getDataHanlder() { + return dataHanlder; + } - public void setDataHanlder(IExcelDataHandler dataHanlder) { - this.dataHanlder = 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 index 90aee6b..bf9cb4e 100644 --- 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 @@ -10,128 +10,128 @@ import org.apache.poi.hssf.util.HSSFColor; */ 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 boolean addIndex; - /** - * 表头颜色 - */ - 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; - } - - public boolean isAddIndex() { - return addIndex; - } - - public void setAddIndex(boolean addIndex) { - this.addIndex = addIndex; - } + /** + * 表格名称 + */ + private String title; + + /** + * 表格名称 + */ + private short titleHeight = 20; + + /** + * 第二行名称 + */ + private String secondTitle; + + /** + * 表格名称 + */ + private short secondTitleHeight = 8; + /** + * sheetName + */ + private String sheetName; + /** + * 过滤的属性 + */ + private String[] exclusions; + /** + * 是否添加需要需要 + */ + private boolean addIndex; + /** + * 表头颜色 + */ + private short color = HSSFColor.WHITE.index; + /** + * 属性说明行的颜色 例如:HSSFColor.SKY_BLUE.index 默认 + */ + private short headerColor = HSSFColor.SKY_BLUE.index; + 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; + } + + public short getColor() { + return color; + } + + public String[] getExclusions() { + return exclusions; + } + + public short getHeaderColor() { + return headerColor; + } + + public String getSecondTitle() { + return secondTitle; + } + + public short getSecondTitleHeight() { + return (short) (secondTitleHeight * 50); + } + + public String getSheetName() { + return sheetName; + } + + public String getTitle() { + return title; + } + + public short getTitleHeight() { + return (short) (titleHeight * 50); + } + + public boolean isAddIndex() { + return addIndex; + } + + public void setAddIndex(boolean addIndex) { + this.addIndex = addIndex; + } + + public void setColor(short color) { + this.color = color; + } + + public void setExclusions(String[] exclusions) { + this.exclusions = exclusions; + } + + public void setHeaderColor(short headerColor) { + this.headerColor = headerColor; + } + + public void setSecondTitle(String secondTitle) { + this.secondTitle = secondTitle; + } + + public void setSecondTitleHeight(short secondTitleHeight) { + this.secondTitleHeight = secondTitleHeight; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setTitleHeight(short titleHeight) { + this.titleHeight = titleHeight; + } } 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 index 1644e50..8763bbb 100644 --- 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 @@ -10,102 +10,102 @@ import org.jeecgframework.poi.handler.inter.IExcelVerifyHandler; * @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; - } + /** + * 表格标题行数,默认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 getHeadRows() { + return headRows; + } + + public int getKeyIndex() { + return keyIndex; + } + + public String getSaveUrl() { + return saveUrl; + } + + public int getSheetNum() { + return sheetNum; + } + + public int getStartRows() { + return startRows; + } + + public int getTitleRows() { + return titleRows; + } + + public IExcelVerifyHandler getVerifyHanlder() { + return verifyHanlder; + } + + public boolean isNeedSave() { + return needSave; + } + + public void setHeadRows(int headRows) { + this.headRows = headRows; + } + + public void setKeyIndex(int keyIndex) { + this.keyIndex = keyIndex; + } + + public void setNeedSave(boolean needSave) { + this.needSave = needSave; + } + + public void setSaveUrl(String saveUrl) { + this.saveUrl = saveUrl; + } + + public void setSheetNum(int sheetNum) { + this.sheetNum = sheetNum; + } + + public void setStartRows(int startRows) { + this.startRows = startRows; + } + + public void setTitleRows(int titleRows) { + this.titleRows = titleRows; + } + + public void setVerifyHanlder(IExcelVerifyHandler verifyHanlder) { + this.verifyHanlder = verifyHanlder; + } } 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 index ba0c7b2..55b1cd6 100644 --- 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 @@ -7,95 +7,92 @@ package org.jeecgframework.poi.excel.entity; * @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; - } +public class TemplateExportParams extends ExcelBaseParams { + + /** + * 模板的路径 + */ + private String templateUrl; + + /** + * 需要导出的第几个 sheetNum,默认是第0个 + */ + private int sheetNum = 0; + + /** + * 这只sheetName 不填就使用原来的 + */ + private String sheetName; + + /** + * 表格列标题行数,默认1 + */ + private int headingRows = 1; + + /** + * 表格列标题开始行,默认1 + */ + private int headingStartRow = 2; + + 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; + } + + public int getHeadingRows() { + return headingRows; + } + + public int getHeadingStartRow() { + return headingStartRow; + } + + public String getSheetName() { + return sheetName; + } + + public int getSheetNum() { + return sheetNum; + } + + public String getTemplateUrl() { + return templateUrl; + } + + public void setHeadingRows(int headingRows) { + this.headingRows = headingRows; + } + + public void setHeadingStartRow(int headingStartRow) { + this.headingStartRow = headingStartRow; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public void setSheetNum(int sheetNum) { + this.sheetNum = sheetNum; + } + + public void setTemplateUrl(String templateUrl) { + this.templateUrl = templateUrl; + } } 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 index 5a3e2ed..725b4fb 100644 --- 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 @@ -9,9 +9,8 @@ import java.util.Comparator; */ public class ComparatorExcelField implements Comparator { - - public int compare(ExcelExportEntity prev,ExcelExportEntity next) { - return prev.getOrderNum() - next.getOrderNum(); - } + 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 index 548de80..68fbc7e 100644 --- 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 @@ -2,93 +2,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 - */ - protected String name; - /** - * 对应type - */ - private int type = 1; - /** - * 数据库格式 - */ - 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; - } + /** + * 对应name + */ + protected String name; + /** + * 对应type + */ + private int type = 1; + /** + * 数据库格式 + */ + private String databaseFormat; + /** + * 导出日期格式 + */ + private String format; + /** + * 导出日期格式 + */ + private String[] replace; + /** + * set/get方法 + */ + private Method method; + + private List methods; + + public String getDatabaseFormat() { + return databaseFormat; + } + + public String getFormat() { + return format; + } + + public Method getMethod() { + return method; + } + + public List getMethods() { + return methods; + } + + public String getName() { + return name; + } + + public String[] getReplace() { + return replace; + } + + public int getType() { + return type; + } + + public void setDatabaseFormat(String databaseFormat) { + this.databaseFormat = databaseFormat; + } + + public void setFormat(String format) { + this.format = format; + } + + public void setMethod(Method method) { + this.method = method; + } + + public void setMethods(List methods) { + this.methods = methods; + } + + public void setName(String name) { + this.name = name; + } + + public void setReplace(String[] replace) { + this.replace = replace; + } + + public void setType(int type) { + this.type = type; + } } 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 index 2c76411..84c986b 100644 --- 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 @@ -2,7 +2,6 @@ package org.jeecgframework.poi.excel.entity.params; import java.util.Map; - /** * Excel 对于的 Collection * @@ -12,41 +11,40 @@ import java.util.Map; */ 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; - } + /** + * 集合对应的名称 + */ + private String name; + /** + * 实体对象 + */ + private Class type; + /** + * 这个list下面的参数集合实体对象 + */ + private Map excelParams; + + public Map getExcelParams() { + return excelParams; + } + + public String getName() { + return name; + } + + public Class getType() { + return type; + } + + public void setExcelParams(Map excelParams) { + this.excelParams = excelParams; + } + + public void setName(String name) { + this.name = name; + } + + public void setType(Class type) { + this.type = type; + } } 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 index 09d62ad..36009a2 100644 --- 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 @@ -10,150 +10,150 @@ import java.util.List; */ public class ExcelExportEntity extends ExcelBaseEntity { - public ExcelExportEntity() { - - } - - public ExcelExportEntity(String name) { - super.name = name; - } - - public ExcelExportEntity(String name, Object key) { - super.name = name; - this.key = key; - } - - public ExcelExportEntity(String name, Object key, int width) { - super.name = name; - this.width = width; - this.key = key; - } - - /** - * 如果是MAP导出,这个是map的key - */ - private Object key; - - private int width = 10; - - private int height = 10; - /** - * 图片的类型,1是文件,2是数据库 - */ - private int exportImageType = 0; - /** - * 排序顺序 - */ - private int orderNum = 0; - /** - * 是否支持换行 - */ - 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; - } - - public Object getKey() { - return key; - } - - public void setKey(Object key) { - this.key = key; - } + /** + * 如果是MAP导出,这个是map的key + */ + private Object key; + + private int width = 10; + + private int height = 10; + + /** + * 图片的类型,1是文件,2是数据库 + */ + private int exportImageType = 0; + + /** + * 排序顺序 + */ + private int orderNum = 0; + + /** + * 是否支持换行 + */ + private boolean isWrap; + + /** + * 是否需要合并 + */ + private boolean needMerge; + /** + * 单元格纵向合并 + */ + private boolean mergeVertical; + /** + * 合并依赖 + */ + private int[] mergeRely; + /** + * cell 函数 + */ + private String cellFormula; + private List list; + public ExcelExportEntity() { + + } + public ExcelExportEntity(String name) { + super.name = name; + } + public ExcelExportEntity(String name, Object key) { + super.name = name; + this.key = key; + } + + public ExcelExportEntity(String name, Object key, int width) { + super.name = name; + this.width = width; + this.key = key; + } + + public String getCellFormula() { + return cellFormula; + } + + public int getExportImageType() { + return exportImageType; + } + + public int getHeight() { + return height; + } + + public Object getKey() { + return key; + } + + public List getList() { + return list; + } + + public int[] getMergeRely() { + return mergeRely; + } + + public int getOrderNum() { + return orderNum; + } + + public int getWidth() { + return width; + } + + public boolean isMergeVertical() { + return mergeVertical; + } + + public boolean isNeedMerge() { + return needMerge; + } + + public boolean isWrap() { + return isWrap; + } + + public void setCellFormula(String cellFormula) { + this.cellFormula = cellFormula; + } + + public void setExportImageType(int exportImageType) { + this.exportImageType = exportImageType; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setKey(Object key) { + this.key = key; + } + + public void setList(List list) { + this.list = list; + } + + public void setMergeRely(int[] mergeRely) { + this.mergeRely = mergeRely; + } + + public void setMergeVertical(boolean mergeVertical) { + this.mergeVertical = mergeVertical; + } + + public void setNeedMerge(boolean needMerge) { + this.needMerge = needMerge; + } + + public void setOrderNum(int orderNum) { + this.orderNum = orderNum; + } + + public void setWidth(int width) { + this.width = width; + } + + public void setWrap(boolean isWrap) { + this.isWrap = isWrap; + } } 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 index 451c44f..fd0ae17 100644 --- 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 @@ -1,81 +1,82 @@ 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; - } + /** + * 对应 Collection NAME + */ + private String collectionName; + /** + * 保存图片的地址 + */ + private String saveUrl; + /** + * 保存图片的类型,1是文件,2是数据库 + */ + private int saveType; + /** + * 对应exportType + */ + private String classType; + /** + * 校驗參數 + */ + private ExcelVerifyEntity verify; + + private List list; + + public String getClassType() { + return classType; + } + + public String getCollectionName() { + return collectionName; + } + + public List getList() { + return list; + } + + public int getSaveType() { + return saveType; + } + + public String getSaveUrl() { + return saveUrl; + } + + public ExcelVerifyEntity getVerify() { + return verify; + } + + public void setClassType(String classType) { + this.classType = classType; + } + + public void setCollectionName(String collectionName) { + this.collectionName = collectionName; + } + + public void setList(List list) { + this.list = list; + } + + public void setSaveType(int saveType) { + this.saveType = saveType; + } + + public void setSaveUrl(String saveUrl) { + this.saveUrl = saveUrl; + } + + 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 index ac931da..5a47d7a 100644 --- 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 @@ -8,120 +8,137 @@ package org.jeecgframework.poi.excel.entity.params; */ 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; - } + /** + * 接口校验 + * + * @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 int getMaxLength() { + return maxLength; + } + + public int getMinLength() { + return minLength; + } + + public String getRegex() { + return regex; + } + + public String getRegexTip() { + return regexTip; + } + + public boolean isEmail() { + return isEmail; + } + + public boolean isInterHandler() { + return interHandler; + } + + public boolean isMobile() { + return isMobile; + } + + public boolean isNotNull() { + return notNull; + } + + public boolean isTel() { + return isTel; + } + + public void setEmail(boolean isEmail) { + this.isEmail = isEmail; + } + + public void setInterHandler(boolean interHandler) { + this.interHandler = interHandler; + } + + public void setMaxLength(int maxLength) { + this.maxLength = maxLength; + } + + public void setMinLength(int minLength) { + this.minLength = minLength; + } + + public void setMobile(boolean isMobile) { + this.isMobile = isMobile; + } + + public void setNotNull(boolean notNull) { + this.notNull = notNull; + } + + public void setRegex(String regex) { + this.regex = regex; + } + + public void setRegexTip(String regexTip) { + this.regexTip = regexTip; + } + + public void setTel(boolean isTel) { + this.isTel = isTel; + } } 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 index a7c1626..d087151 100644 --- 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 @@ -11,59 +11,59 @@ public class MergeEntity { /** * 合并开始行 */ - private int startRow; + private int startRow; /** * 合并结束行 */ - private int endRow; + private int endRow; /** * 文字 */ - private String text; + private String text; /** * 依赖关系文本 */ private List relyList; - public MergeEntity(){ + public MergeEntity() { } - public MergeEntity(String text,int startRow,int endRow){ + 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 List getRelyList() { + return relyList; } - public String getText() { - return text; + public int getStartRow() { + return startRow; } - public void setText(String text) { - this.text = text; + public String getText() { + return text; } - public List getRelyList() { - return relyList; + public void setEndRow(int endRow) { + this.endRow = endRow; } public void setRelyList(List relyList) { this.relyList = relyList; } + + public void setStartRow(int startRow) { + this.startRow = startRow; + } + + public void setText(String text) { + this.text = text; + } } 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 index 9b4a9c0..f4f425e 100644 --- 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 @@ -13,51 +13,51 @@ import org.apache.poi.ss.usermodel.Workbook; @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; - } + /** + * 结果集 + */ + private List list; + + /** + * 是否存在校验失败 + */ + private boolean verfiyFail; + + /** + * 数据源 + */ + private Workbook workbook; + public ExcelImportResult() { + + } + public ExcelImportResult(List list, boolean verfiyFail, Workbook workbook) { + this.list = list; + this.verfiyFail = verfiyFail; + this.workbook = workbook; + } + + public List getList() { + return list; + } + + public Workbook getWorkbook() { + return workbook; + } + + public boolean isVerfiyFail() { + return verfiyFail; + } + + public void setList(List list) { + this.list = list; + } + + public void setVerfiyFail(boolean verfiyFail) { + this.verfiyFail = verfiyFail; + } + + 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 index d9f1bbb..b3c8da6 100644 --- 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 @@ -7,42 +7,42 @@ package org.jeecgframework.poi.excel.entity.result; * @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; - } + /** + * 是否正确 + */ + 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 String getMsg() { + return msg; + } + + public boolean isSuccess() { + return success; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public void setSuccess(boolean success) { + this.success = success; + } } 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 index f37941f..05abc02 100644 --- 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 @@ -6,12 +6,12 @@ package org.jeecgframework.poi.excel.entity.vo; */ public interface PoiBaseConstants { - public static String GET = "get"; + public static String GET = "get"; - public static String SET = "set"; - - public static String IS = "is"; - - public static String IS_ADD_INDEX = "isAddIndex"; + public static String SET = "set"; + + public static String IS = "is"; + + public static String IS_ADD_INDEX = "isAddIndex"; } 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 index e9b628c..1ccaf47 100644 --- 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 @@ -38,343 +38,326 @@ import org.slf4j.LoggerFactory; */ public class ExcelExportServer extends ExcelExportBase { - private final static Logger logger = LoggerFactory - .getLogger(ExcelExportServer.class); + private final static Logger logger = LoggerFactory.getLogger(ExcelExportServer.class); - private static final short cellFormat = HSSFDataFormat - .getBuiltinFormat("TEXT"); + private static final short cellFormat = HSSFDataFormat.getBuiltinFormat("TEXT"); - // 最大行数,超过自动多Sheet - private final int MAX_NUM = 60000; + // 最大行数,超过自动多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(); - if (entity.isAddIndex()) { - excelParams.add(indexExcelEntity()); - } - // 得到所有字段 - Field fileds[] = POIPublicUtil.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); - setCurrentIndex(1); - 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); + 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; + } - 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); - } + /** + * 创建 表头改变 + * + * @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; + } - } catch (Exception e) { - logger.error(e.getMessage(),e.fillInStackTrace()); - throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, - e.getCause()); - } - } + 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(); + if (entity.isAddIndex()) { + excelParams.add(indexExcelEntity()); + } + // 得到所有字段 + Field fileds[] = POIPublicUtil.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); + setCurrentIndex(1); + 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); - private ExcelExportEntity indexExcelEntity() { - ExcelExportEntity entity = new ExcelExportEntity(); - entity.setOrderNum(0); - entity.setName("序号"); - entity.setWidth(10); - entity.setFormat(PoiBaseConstants.IS_ADD_INDEX); - return entity; - } + 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); + } - 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; - } + } catch (Exception e) { + logger.error(e.getMessage(), e.fillInStackTrace()); + throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause()); + } + } - /** - * 创建表头 - * - * @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; + public void createSheetForMap(HSSFWorkbook workbook, ExportParams entity, + List entityList, + Collection> dataSet) { + if (workbook == null || entity == null || entityList == 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(); + if (entity.isAddIndex()) { + excelParams.add(indexExcelEntity()); + } + excelParams.addAll(entityList); + sortAllParams(excelParams); + int index = createHeaderAndTitle(entity, sheet, workbook, excelParams); + int titleHeight = index; + setCellWith(excelParams, sheet); + short rowHeight = getRowHeight(excelParams); + setCurrentIndex(1); + 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) { + createSheetForMap(workbook, entity, entityList, dataSet); + } - /** - * 判断表头是只有一行还是两行 - * - * @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; - } + } catch (Exception e) { + e.printStackTrace(); + logger.error(e.getMessage(), e.fillInStackTrace()); + throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause()); + } + } - /** - * 创建 表头改变 - * - * @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; - } + 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; + } - /** - * 字段说明的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; - } + /** + * 创建表头 + * + * @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; - /** - * 表明的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; - } + /** + * 表明的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 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; - } + 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; - } + /** + * 判断表头是只有一行还是两行 + * + * @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; + } - 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"); - } + 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"); + } - public void createSheetForMap(HSSFWorkbook workbook, ExportParams entity, - List entityList, - Collection> dataSet) { - if (workbook == null || entity == null || entityList == 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(); - if (entity.isAddIndex()) { - excelParams.add(indexExcelEntity()); - } - excelParams.addAll(entityList); - sortAllParams(excelParams); - int index = createHeaderAndTitle(entity, sheet, workbook, - excelParams); - int titleHeight = index; - setCellWith(excelParams, sheet); - short rowHeight = getRowHeight(excelParams); - setCurrentIndex(1); - 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); + /** + * 字段说明的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; + } - its = dataSet.iterator(); - for (int i = 0, le = tempList.size(); i < le; i++) { - its.next(); - its.remove(); - } - // 发现还有剩余list 继续循环创建Sheet - if (dataSet.size() > 0) { - createSheetForMap(workbook, entity, entityList, dataSet); - } + 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; + } - } catch (Exception e) { - e.printStackTrace(); - logger.error(e.getMessage(),e.fillInStackTrace()); - throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, - e.getCause()); - } - } + private ExcelExportEntity indexExcelEntity() { + ExcelExportEntity entity = new ExcelExportEntity(); + entity.setOrderNum(0); + entity.setName("序号"); + entity.setWidth(10); + entity.setFormat(PoiBaseConstants.IS_ADD_INDEX); + return entity; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java index b23e1ac..af48218 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExcelExportBase.java @@ -39,405 +39,382 @@ import org.jeecgframework.poi.util.POIPublicUtil; */ public abstract class ExcelExportBase extends ExportBase { - private int currentIndex = 0; + private int currentIndex = 0; - /** - * 合并单元格 - * - * @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)); - } + 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; + } - } + /** + * 创建 最主要的 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; + int indexKey = createIndexCell(row, styles, index, excelParams.get(0)); + cellNum += indexKey; + for (int k = indexKey, 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 = indexKey, 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; - /** - * 字符为空的情况下判断 - * - * @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)); - } - } + /** + * 图片类型的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 = POIPublicUtil.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 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 int createIndexCell(Row row, Map styles, int index, + ExcelExportEntity excelExportEntity) { + if (excelExportEntity.getName().equals("序号") + && excelExportEntity.getFormat().equals(PoiBaseConstants.IS_ADD_INDEX)) { + createStringCell(row, 0, currentIndex + "", + index % 2 == 0 ? getStyles(styles, false, false) : getStyles(styles, true, false), + null); + currentIndex = currentIndex + 1; + return 1; + } + return 0; + } - 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; - } + /** + * 创建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); + } + } + } - 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; - } + 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; + } - /** - * 创建 最主要的 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; - int indexKey = createIndexCell(row, styles, index, excelParams.get(0)); - cellNum += indexKey; - for (int k = indexKey, 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 = indexKey, 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; + /** + * 创建文本类型的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); + } + } - } + /** + * 获取一个单元格的值,确保这个单元格必须有值,不然向上查询 + * + * @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 int createIndexCell(Row row, Map styles, - int index, ExcelExportEntity excelExportEntity) { - if (excelExportEntity.getName().equals("序号") - && excelExportEntity.getFormat().equals( - PoiBaseConstants.IS_ADD_INDEX)) { - createStringCell(row, 0, currentIndex + "", - index % 2 == 0 ? getStyles(styles, false, false) - : getStyles(styles, true, false), null); - currentIndex = currentIndex + 1; - return 1; - } - return 0; - } + /** + * 获取导出报表的字段总长度 + * + * @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; + } - public CellStyle getStyles(Map styles, boolean b, - boolean wrap) { - return null; - } + /** + * 获取图片类型,设置图片插入类型 + * + * @param value + * @return + * @Author JueYue + * @date 2013年11月25日 + */ + public int getImageType(byte[] value) { + String type = POIPublicUtil.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; + } - /** - * 创建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); - } - } - } + 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; + } - 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++; - } - } - } + public CellStyle getStyles(Map styles, boolean b, boolean wrap) { + return null; + } - /** - * 创建文本类型的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); - } - } + /** + * 处理合并单元格 + * + * @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)); + } + } - /** - * 图片类型的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 = POIPublicUtil.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 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 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 value - * @return - * @Author JueYue - * @date 2013年11月25日 - */ - public int getImageType(byte[] value) { - String type = POIPublicUtil.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; - } + 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++; + } + } + } - public void setCurrentIndex(int currentIndex) { - this.currentIndex = currentIndex; - } + public void setCurrentIndex(int currentIndex) { + this.currentIndex = currentIndex; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExportBase.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExportBase.java index 8c5de1b..019d54b 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExportBase.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/base/ExportBase.java @@ -28,300 +28,278 @@ import org.jeecgframework.poi.util.POIPublicUtil; */ public class ExportBase { - protected IExcelDataHandler dataHanlder; + protected IExcelDataHandler dataHanlder; - protected List needHanlderList; + 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 (POIPublicUtil.isNotUserExcelUserThis(exclusionsList, field, - targetId)) { - continue; - } - // 首先判断Excel 可能一下特殊数据用户回自定义处理 - if (field.getAnnotation(Excel.class) != null) { - excelParams.add(createExcelExportEntity(field, targetId, - pojoClass, getMethods)); - } else if (POIPublicUtil.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, POIPublicUtil.getClassFields(clz), - list, clz, null); - excelEntity = new ExcelExportEntity(); - excelEntity.setName(getExcelName(excel.name(), targetId)); - excelEntity - .setOrderNum(getCellOrder(excel.orderNum(), targetId)); - excelEntity.setMethod(POIPublicUtil.getMethod(field.getName(), - pojoClass)); - excelEntity.setList(list); - excelParams.add(excelEntity); - } else { - List newMethods = new ArrayList(); - if (getMethods != null) { - newMethods.addAll(getMethods); - } - newMethods.add(POIPublicUtil.getMethod(field.getName(), - pojoClass)); - ExcelEntity excel = field.getAnnotation(ExcelEntity.class); - getAllExcelField(exclusions, - StringUtils.isNotEmpty(excel.id()) ? excel.id() - : targetId, POIPublicUtil.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(); + try { + excelEntity.setType(excel.type()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + 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 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(); - try { - excelEntity.setType(excel.type()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - 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; - } + 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; + } - /** - * 判断在这个单元格显示的名称 - * - * @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 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 (POIPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) { + continue; + } + // 首先判断Excel 可能一下特殊数据用户回自定义处理 + if (field.getAnnotation(Excel.class) != null) { + excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods)); + } else if (POIPublicUtil.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, POIPublicUtil.getClassFields(clz), list, clz, null); + excelEntity = new ExcelExportEntity(); + excelEntity.setName(getExcelName(excel.name(), targetId)); + excelEntity.setOrderNum(getCellOrder(excel.orderNum(), targetId)); + excelEntity.setMethod(POIPublicUtil.getMethod(field.getName(), pojoClass)); + excelEntity.setList(list); + excelParams.add(excelEntity); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods.add(POIPublicUtil.getMethod(field.getName(), pojoClass)); + ExcelEntity excel = field.getAnnotation(ExcelEntity.class); + getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() + : targetId, POIPublicUtil.getClassFields(field.getType()), excelParams, + field.getType(), newMethods); + } + } + } - /** - * 获取这个字段的顺序 - * - * @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; - } + /** + * 获取这个字段的顺序 + * + * @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; - } - } + /** + * 获取填如这个cell的值,提供一些附加功能 + * + * @param entity + * @param obj + * @return + * @throws Exception + */ + public Object getCellValue(ExcelExportEntity entity, Object obj) throws Exception { + Object value; + if (obj instanceof Map) { + return ((Map) obj).get(entity.getKey()); + } else { + 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(); + } - /** - * 注解到导出对象的转换 - * - * @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(POIPublicUtil.getMethod(fieldname, pojoClass)); - } + /** + * 注解到导出对象的转换 + * + * @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(POIPublicUtil.getMethod(fieldname, pojoClass)); + } - /** - * 根据注解获取行高 - * - * @param excelParams - * @return - */ - 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); - } + /** + * 判断在这个单元格显示的名称 + * + * @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; + } - /** - * 对字段根据用户设置排序 - */ - 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; + } - /** - * 获取填如这个cell的值,提供一些附加功能 - * - * @param entity - * @param obj - * @return - * @throws Exception - */ - public Object getCellValue(ExcelExportEntity entity, Object obj) - throws Exception { - Object value; - if (obj instanceof Map) { - return ((Map) obj).get(entity.getKey()); - } else { - 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(); - } + /** + * 根据注解获取行高 + * + * @param excelParams + * @return + */ + 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); + } - 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; - } + /** + * 判断字符串是否是整数 + */ + public boolean isInteger(String value) { + try { + Integer.parseInt(value); + return true; + } catch (NumberFormatException e) { + return false; + } + } - 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; - } + 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; + } - /** - * 多个反射获取值 - * - * @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 sortAllParams(List excelParams) { + Collections.sort(excelParams, new ComparatorExcelField()); + for (ExcelExportEntity entity : excelParams) { + if (entity.getList() != null) { + Collections.sort(entity.getList(), new ComparatorExcelField()); + } + } + } } 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 index e23e39f..2d685ce 100644 --- 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 @@ -32,232 +32,219 @@ import org.jeecgframework.poi.util.POIPublicUtil; * @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); - if (StringUtils.isNotEmpty(params.getSheetName())) { - wb.setSheetName(0, params.getSheetName()); - } - // step 3. 解析模板 - parseTemplate(wb.getSheetAt(0), map); - if (dataSet != null) { - // step 4. 正常的数据填充 - 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; - } + /** + * 往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[] = POIPublicUtil.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); + } - /** - * 克隆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()); + 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); + if (StringUtils.isNotEmpty(params.getSheetName())) { + wb.setSheetName(0, params.getSheetName()); + } + // step 3. 解析模板 + parseTemplate(wb.getSheetAt(0), map); + if (dataSet != null) { + // step 4. 正常的数据填充 + 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[] = POIPublicUtil.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 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 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; + /** + * 获取表头数据,设置表头的序号 + * + * @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); - } - } - } + /** + * 通过遍历过去对象值 + * + * @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 = POIPublicUtil.getMethod(paramsArr[index], object.getClass()).invoke(object, + new Object[] {}); + } + return (index == paramsArr.length - 1) ? (object == null ? "" : object.toString()) + : getValueDoWhile(object, paramsArr, ++index); + } - /** - * 给每个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); - } - } + 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); + } + } + } - /** - * 获取参数值 - * - * @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() : ""; - } + /** + * 给每个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 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 = POIPublicUtil.getMethod(paramsArr[index], - object.getClass()).invoke(object, new Object[] {}); - } - return (index == paramsArr.length - 1) ? (object == null ? "" : object - .toString()) : getValueDoWhile(object, paramsArr, ++index); - } + /** + * 对导出序列进行排序和塞选 + * + * @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); + } } 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 index c512acb..24f7900 100644 --- 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 @@ -27,164 +27,159 @@ import org.slf4j.LoggerFactory; */ public class CellValueServer { - private static final Logger logger = LoggerFactory - .getLogger(CellValueServer.class); + private static final Logger logger = LoggerFactory.getLogger(CellValueServer.class); - private List hanlderList = null; + 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 cell + * @param entity + * @return + */ + private Object getCellValue(String xclass, Cell cell, ExcelImportEntity entity) { + if (cell == null) { + return ""; + } + 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; + } - /** - * 根据返回类型获取返回值 - * - * @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); - } - } + /** + * 获取日期类型数据 + * + * @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; + } - /** - * 调用处理接口处理值 - * - * @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; - } + /** + * 获取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 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 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 xclass - * @param cell - * @param entity - * @return - */ - private Object getCellValue(String xclass, Cell cell, - ExcelImportEntity entity) { - if(cell == null){ - return ""; - } - 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; - } + /** + * 调用处理接口处理值 + * + * @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; + } - /** - * 获取日期类型数据 - * - * @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; - } + /** + * 替换值 + * + * @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; + } } 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 index 3755902..6ee67fc 100644 --- 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 @@ -52,548 +52,514 @@ import org.slf4j.LoggerFactory; */ @SuppressWarnings({ "rawtypes", "unchecked", "hiding" }) public class ExcelImportServer { - - private final static Logger logger = LoggerFactory.getLogger(ExcelImportServer.class); - private CellValueServer cellValueServer; + private final static Logger logger = LoggerFactory.getLogger(ExcelImportServer.class); - private VerifyHandlerServer verifyHandlerServer; + private CellValueServer cellValueServer; - private boolean verfiyFail = false; + private VerifyHandlerServer verifyHandlerServer; - public ExcelImportServer() { - cellValueServer = new CellValueServer(); - verifyHandlerServer = new VerifyHandlerServer(); - } + private boolean verfiyFail = false; - /** - * 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(logger.isDebugEnabled()){ - logger.debug(" start to read excel by is ,startTime is {}", new Date().getTime()); - } - if (isXSSFWorkbook) { - pictures = POIPublicUtil.getSheetPictrues07( - (XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book); - } else { - pictures = POIPublicUtil.getSheetPictrues03( - (HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book); - } - if(logger.isDebugEnabled()){ - logger.debug(" end to read excel by is ,endTime is {}", new Date().getTime()); - } - result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, - params, pictures)); - if(logger.isDebugEnabled()){ - logger.debug(" end to read excel list by pos ,endTime is {}", new Date().getTime()); - } - } - if (params.isNeedSave()) { - saveThisExcel(params, pojoClass, isXSSFWorkbook, book); - } - return new ExcelImportResult(result, verfiyFail, book); - } + public ExcelImportServer() { + cellValueServer = new CellValueServer(); + verifyHandlerServer = new VerifyHandlerServer(); + } - private void saveThisExcel(ImportParams params, Class pojoClass, - boolean isXSSFWorkbook, Workbook book) throws Exception { - String path = POIPublicUtil.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(); - } + /** + * 把这个注解解析放到类型对象中 + * + * @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); - /** - * 获取保存的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; - } - 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[] = POIPublicUtil.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 = POIPublicUtil.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; - } + /*** + * 向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) POIPublicUtil.getMethod(param.getName(), + object.getClass()).invoke(object, new Object[] {}); + Object entity = POIPublicUtil.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 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; - } - } + /** + * 获取需要导出的全部字段 + * + * + * @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 (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + continue; + } + if (POIPublicUtil.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, POIPublicUtil.getClassFields(clz), clz, temp, null); + collection.setExcelParams(temp); + excelCollection.add(collection); + } else if (POIPublicUtil.isJavaClass(field)) { + addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, excelParams); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods.add(POIPublicUtil.getMethod(field.getName(), pojoClass)); + getAllExcelField(targetId, POIPublicUtil.getClassFields(field.getType()), + excelParams, excelCollection, field.getType(), newMethods); + } + } + } - /** - * 获取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(); - } + 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(POIPublicUtil.getMethod(fieldname, pojoClass, field.getType())); + if (StringUtils.isEmpty(excel.importFormat())) { + excelEntity.setFormat(excel.format()); + } else { + excelEntity.setFormat(excel.importFormat()); + } + } - /** - * - * @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 += "." + POIPublicUtil.getFileExtendName(data); - if (excelParams.get(titleString).getSaveType() == 1) { - String path = POIPublicUtil.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); - } - } + 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 (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + continue; + } + if (POIPublicUtil.isJavaClass(field)) { + addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, temp); + } else { + List newMethods = new ArrayList(); + if (getMethods != null) { + newMethods.addAll(getMethods); + } + newMethods + .add(POIPublicUtil.getMethod(field.getName(), pojoClass, field.getType())); + getExcelFieldList(targetId, POIPublicUtil.getClassFields(field.getType()), + field.getType(), temp, newMethods); + } + } + } - /** - * 获取保存的真实路径 - * - * @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(); - } + /** + * 判断在这个单元格显示的名称 + * + * @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; + } - /*** - * 向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) POIPublicUtil.getMethod( - param.getName(), object.getClass()).invoke(object, - new Object[] {}); - Object entity = POIPublicUtil.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); - } - } + 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 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); - } - } + /** + * 获取导入校验参数 + * + * @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; + } - /** - * 多个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); - } + /** + * 获取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(); + } - 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; - } + /** + * 获取保存的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; + } + return params.getSaveUrl(); + } - /** - * 获取需要导出的全部字段 - * - * - * @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 (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { - continue; - } - if (POIPublicUtil.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, - POIPublicUtil.getClassFields(clz), clz, temp, null); - collection.setExcelParams(temp); - excelCollection.add(collection); - } else if (POIPublicUtil.isJavaClass(field)) { - addEntityToMap(targetId, field, excelEntity, pojoClass, - getMethods, excelParams); - } else { - List newMethods = new ArrayList(); - if (getMethods != null) { - newMethods.addAll(getMethods); - } - newMethods.add(POIPublicUtil.getMethod(field.getName(), - pojoClass)); - getAllExcelField(targetId, - POIPublicUtil.getClassFields(field.getType()), - excelParams, excelCollection, field.getType(), - newMethods); - } - } - } + /** + * 获取保存的真实路径 + * + * @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(); + } - 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 (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { - continue; - } - if (POIPublicUtil.isJavaClass(field)) { - addEntityToMap(targetId, field, excelEntity, pojoClass, - getMethods, temp); - } else { - List newMethods = new ArrayList(); - if (getMethods != null) { - newMethods.addAll(getMethods); - } - newMethods.add(POIPublicUtil.getMethod(field.getName(), - pojoClass, field.getType())); - getExcelFieldList(targetId, - POIPublicUtil.getClassFields(field.getType()), - field.getType(), temp, newMethods); - } - } - } + 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[] = POIPublicUtil.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 = POIPublicUtil.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 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); + /** + * 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 (logger.isDebugEnabled()) { + logger.debug(" start to read excel by is ,startTime is {}", new Date().getTime()); + } + if (isXSSFWorkbook) { + pictures = POIPublicUtil.getSheetPictrues07((XSSFSheet) book.getSheetAt(i), + (XSSFWorkbook) book); + } else { + pictures = POIPublicUtil.getSheetPictrues03((HSSFSheet) book.getSheetAt(i), + (HSSFWorkbook) book); + } + if (logger.isDebugEnabled()) { + logger.debug(" end to read excel by is ,endTime is {}", new Date().getTime()); + } + result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, params, pictures)); + if (logger.isDebugEnabled()) { + logger.debug(" end to read excel list by pos ,endTime is {}", new Date().getTime()); + } + } + if (params.isNeedSave()) { + saveThisExcel(params, pojoClass, isXSSFWorkbook, book); + } + return new ExcelImportResult(result, verfiyFail, book); + } - } + /** + * 保存字段值(获取值,校验值,追加错误信息) + * + * @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; + } + } - /** - * 获取导入校验参数 - * - * @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; - } + /** + * + * @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 += "." + POIPublicUtil.getFileExtendName(data); + if (excelParams.get(titleString).getSaveType() == 1) { + String path = POIPublicUtil.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); + } + } - 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(POIPublicUtil.getMethod(fieldname, pojoClass, - field.getType())); - if (StringUtils.isEmpty(excel.importFormat())) { - excelEntity.setFormat(excel.format()); - } else { - excelEntity.setFormat(excel.importFormat()); - } - } + private void saveThisExcel(ImportParams params, Class pojoClass, boolean isXSSFWorkbook, + Workbook book) throws Exception { + String path = POIPublicUtil.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(); + } - /** - * 判断在这个单元格显示的名称 - * - * @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; - } + /** + * 多个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); + } + + /** + * + * @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); + } + } } 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 index b435173..540ba3c 100644 --- 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 @@ -12,125 +12,122 @@ import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; */ 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 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 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 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}$/"); + 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); - } + /** + * 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 - * @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 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); - } + /** + * 电话校验 + * + * @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 + * @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 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 + * @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); - } + /** + * 非空校验 + * + * @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 + * @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 index a572dbc..73d1b84 100644 --- 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 @@ -12,62 +12,56 @@ import org.jeecgframework.poi.handler.inter.IExcelVerifyHandler; * @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()); + } + } - } + /** + * 校驗數據 + * + * @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 index 8408011..cef3768 100644 --- 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 @@ -10,38 +10,38 @@ import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; */ public class ExcelExportException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private ExcelExportEnum type; + private ExcelExportEnum type; - public ExcelExportException() { - super(); - } - - public ExcelExportException(String message) { - super(message); - } + public ExcelExportException() { + super(); + } - public ExcelExportException(ExcelExportEnum type) { - super(type.getMsg()); - this.type = type; - } + 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) { + public ExcelExportException(ExcelExportEnum type, Throwable cause) { super(type.getMsg(), cause); } - public ExcelExportEnum getType() { - return type; - } + public ExcelExportException(String message) { + super(message); + } - public void setType(ExcelExportEnum type) { - this.type = type; - } + public ExcelExportException(String message, ExcelExportEnum type) { + super(message); + this.type = type; + } + + 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 index 70ac2bc..db2e8bb 100644 --- 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 @@ -9,38 +9,38 @@ import org.jeecgframework.poi.exception.excel.enums.ExcelImportEnum; */ public class ExcelImportException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - private ExcelImportEnum type; + private ExcelImportEnum type; - public ExcelImportException() { - super(); - } - - public ExcelImportException(String message) { - super(message); - } + public ExcelImportException() { + super(); + } - public ExcelImportException(ExcelImportEnum type) { - super(type.getMsg()); - this.type = type; - } + 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) { + public ExcelImportException(ExcelImportEnum type, Throwable cause) { super(type.getMsg(), cause); } - public ExcelImportEnum getType() { - return type; - } + public ExcelImportException(String message) { + super(message); + } - public void setType(ExcelImportEnum type) { - this.type = type; - } + public ExcelImportException(String message, ExcelImportEnum type) { + super(message); + this.type = type; + } + + 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 index c8d6687..ae1a0a4 100644 --- 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 @@ -1,26 +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; - } + 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; - } + 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 index 6898bb1..86c5609 100644 --- 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 @@ -1,25 +1,26 @@ 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; - } + 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; - } + public void setMsg(String msg) { + this.msg = msg; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/WordExportException.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/WordExportException.java index 30e20e0..bd2f190 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/WordExportException.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/WordExportException.java @@ -10,18 +10,18 @@ import org.jeecgframework.poi.exception.word.enmus.WordExportEnum; */ public class WordExportException extends RuntimeException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public WordExportException() { - super(); - } + public WordExportException() { + super(); + } - public WordExportException(String msg) { - super(msg); - } + public WordExportException(String msg) { + super(msg); + } - public WordExportException(WordExportEnum exception) { - super(exception.getMsg()); - } + public WordExportException(WordExportEnum exception) { + super(exception.getMsg()); + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/enmus/WordExportEnum.java b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/enmus/WordExportEnum.java index 10bcb56..fd34f22 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/enmus/WordExportEnum.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/exception/word/enmus/WordExportEnum.java @@ -7,23 +7,22 @@ package org.jeecgframework.poi.exception.word.enmus; * @date 2014年8月9日 下午10:34:58 */ public enum WordExportEnum { - - EXCEL_PARAMS_ERROR("Excel 导出 参数错误"), - EXCEL_HEAD_HAVA_NULL("Excel 表头 有的字段为空"), - EXCEL_NO_HEAD("Excel 没有表头"); - private String msg; + EXCEL_PARAMS_ERROR("Excel 导出 参数错误"), EXCEL_HEAD_HAVA_NULL("Excel 表头 有的字段为空"), EXCEL_NO_HEAD( + "Excel 没有表头"); - WordExportEnum(String msg) { - this.msg = msg; - } + private String msg; - public String getMsg() { - return msg; - } + WordExportEnum(String msg) { + this.msg = msg; + } - public void setMsg(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 index d402c8a..4a821b5 100644 --- 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 @@ -9,29 +9,29 @@ import org.jeecgframework.poi.handler.inter.IExcelDataHandler; * @date 2014年6月20日 上午12:11:52 */ public abstract class ExcelDataHandlerDefaultImpl implements IExcelDataHandler { - /** - * 需要处理的字段 - */ - private String[] needHandlerFields; + /** + * 需要处理的字段 + */ + private String[] needHandlerFields; - @Override - public Object exportHandler(Object obj, String name, Object value) { - return value; - } + @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; + } - @Override - public String[] getNeedHandlerFields() { - return needHandlerFields; - } + @Override + public Object importHandler(Object obj, String name, Object value) { + return value; + } - @Override - public void setNeedHandlerFields(String[] needHandlerFields) { - this.needHandlerFields = needHandlerFields; - } + @Override + public void setNeedHandlerFields(String[] needHandlerFields) { + this.needHandlerFields = needHandlerFields; + } } 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 index 99c1b2a..5f60a75 100644 --- 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 @@ -8,39 +8,39 @@ package org.jeecgframework.poi.handler.inter; */ public interface IExcelDataHandler { - /** - * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 - * - * @return - */ - public String[] getNeedHandlerFields(); + /** + * 导出处理方法 + * + * @param obj + * 当前对象 + * @param name + * 当前字段名称 + * @param value + * 当前值 + * @return + */ + public Object exportHandler(Object obj, String name, Object value); - public void setNeedHandlerFields(String[] fields); + /** + * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 + * + * @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); - /** - * 导入处理方法 当前对象,当前字段名称,当前值 - * - * @param obj - * 当前对象 - * @param name - * 当前字段名称 - * @param value - * 当前值 - * @return - */ - public Object importHandler(Object obj, String name, Object value); + public void setNeedHandlerFields(String[] fields); } 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 index 1dff186..49d3fab 100644 --- 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 @@ -10,32 +10,31 @@ import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; */ public interface IExcelVerifyHandler { - /** - * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 - * - * @return - */ - public String[] getNeedVerifyFields(); + /** + * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 + * + * @return + */ + public String[] getNeedVerifyFields(); - /** - * 导出处理方法 - * - * @param obj - * 当前对象 - * @param name - * 当前字段名称 - * @param value - * 当前值 - * @return - */ - public ExcelVerifyHanlderResult verifyHandler(Object obj, String name, - Object value); + /** + * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 + * + * @return + */ + public void setNeedVerifyFields(String[] arr); - /** - * 获取需要处理的字段,导入和导出统一处理了, 减少书写的字段 - * - * @return - */ - public void setNeedVerifyFields(String[] arr); + /** + * 导出处理方法 + * + * @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/util/POIPublicUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java index 75dd6d2..706f56e 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java @@ -1,9 +1,27 @@ package org.jeecgframework.poi.util; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.poi.POIXMLDocumentPart; -import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.hssf.usermodel.HSSFClientAnchor; +import org.apache.poi.hssf.usermodel.HSSFPicture; +import org.apache.poi.hssf.usermodel.HSSFPictureData; +import org.apache.poi.hssf.usermodel.HSSFShape; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.xssf.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFClientAnchor; +import org.apache.poi.xssf.usermodel.XSSFDrawing; +import org.apache.poi.xssf.usermodel.XSSFPicture; +import org.apache.poi.xssf.usermodel.XSSFShape; +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.ExcelCollection; import org.jeecgframework.poi.excel.annotation.ExcelEntity; @@ -11,284 +29,261 @@ 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 POIPublicUtil { - public static String getWebRootPath(String filePath) { - // 这个path还是要测试的 - String path = POIPublicUtil.class.getClassLoader().getResource("") - .getPath() - + filePath; - path = path.replace("WEB-INF/classes/", ""); - path = path.replace("file:/", ""); - return path; - } + /** + * 彻底创建一个对象 + * + * @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)); + } + } - /** - * 获取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); - } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException("创建对象异常"); + } + return obj; - /** - * 判断是不是集合的实现类 - * - * @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; - } + /** + * 获取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 exportName - * @param targetId - * @return - */ - private static boolean isUseInThis(String exportName, String targetId) { - return targetId == null || exportName.equals("") - || exportName.indexOf("_") < 0 - || exportName.indexOf(targetId) != -1; - } + /** + * @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; + } - /** - * 是不是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; - } + /** + * 获取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; + } - /** - * 彻底创建一个对象 - * - * @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)); - } - } + /** + * 获取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 }); + } - } catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException("创建对象异常"); - } - return obj; + /** + * 获取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; + } - /** - * 获取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; - } + public static String getWebRootPath(String filePath) { + // 这个path还是要测试的 + String path = POIPublicUtil.class.getClassLoader().getResource("").getPath() + filePath; + path = path.replace("WEB-INF/classes/", ""); + path = path.replace("file:/", ""); + return path; + } - /** - * 获取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 clazz + * @return + */ + public static boolean isCollection(Class clazz) { + return Collection.class.isAssignableFrom(clazz); + } - /** - * @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; - } + /** + * 是不是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; + } - /** - * 获取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; - } - } + /** + * 判断是否不要在这个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; + } - /** - * 获取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; - } + /** + * 判断是不是使用 + * + * @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; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java index 2f04c8e..c7fea08 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java @@ -14,32 +14,31 @@ import org.jeecgframework.poi.word.parse.ParseWord07; */ public class WordExportUtil { - /** - * 解析Word2007版本 - * - * @param url - * 模板地址 - * @param map - * 解析数据源 - * @return - */ - public static XWPFDocument exportWord07(String url, Map map) - throws Exception { - return new ParseWord07().parseWord(url, map); - } + /** + * 解析Word2007版本 + * + * @param url + * 模板地址 + * @param map + * 解析数据源 + * @return + */ + public static XWPFDocument exportWord07(String url, Map map) throws Exception { + return new ParseWord07().parseWord(url, map); + } - /** - * 解析Word2007版本 - * - * @param XWPFDocument - * 模板 - * @param map - * 解析数据源 - * @return - */ - public static void exportWord07(XWPFDocument document, - Map map) throws Exception { - new ParseWord07().parseWord(document, map); - } + /** + * 解析Word2007版本 + * + * @param XWPFDocument + * 模板 + * @param map + * 解析数据源 + * @return + */ + public static void exportWord07(XWPFDocument document, Map map) + throws Exception { + new ParseWord07().parseWord(document, map); + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java index 64bf9db..d102062 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java @@ -20,138 +20,143 @@ import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline */ public class JeecgXWPFDocument extends XWPFDocument { - public JeecgXWPFDocument() { - super(); - } - - public JeecgXWPFDocument(OPCPackage opcPackage) throws Exception { - super(opcPackage); - } - - public JeecgXWPFDocument(InputStream in) throws Exception { - super(in); - } - - public void createPicture(String blipId,int id, int width, int height) { - final int EMU = 9525; - width *= EMU; - height *= EMU; - //String blipId = getAllPictures().get(id).getPackageRelationship().getId(); - CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline(); - - String picXml = "" + - "" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""; - - //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData(); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch(XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - //graphicData.set(xmlToken); - - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("Picture " + id); - docPr.setDescr("Generated"); - } - - public void createPicture(XWPFRun run,String blipId, int id, int width, int height) { - final int EMU = 9525; - width *= EMU; - height *= EMU; - CTInline inline = run.getCTR() - .addNewDrawing().addNewInline(); - - String picXml = "" - + "" - + " " - + " " - + " " + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " - + " " + ""; - - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("Picture " + id); - docPr.setDescr("Generated"); - } + public JeecgXWPFDocument() { + super(); + } + + public JeecgXWPFDocument(InputStream in) throws Exception { + super(in); + } + + public JeecgXWPFDocument(OPCPackage opcPackage) throws Exception { + super(opcPackage); + } + + public void createPicture(String blipId, int id, int width, int height) { + final int EMU = 9525; + width *= EMU; + height *= EMU; + //String blipId = getAllPictures().get(id).getPackageRelationship().getId(); + CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline(); + + String picXml = "" + + "" + + " " + + " " + + " " + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + ""; + + //CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData(); + XmlToken xmlToken = null; + try { + xmlToken = XmlToken.Factory.parse(picXml); + } catch (XmlException xe) { + xe.printStackTrace(); + } + inline.set(xmlToken); + //graphicData.set(xmlToken); + + inline.setDistT(0); + inline.setDistB(0); + inline.setDistL(0); + inline.setDistR(0); + + CTPositiveSize2D extent = inline.addNewExtent(); + extent.setCx(width); + extent.setCy(height); + + CTNonVisualDrawingProps docPr = inline.addNewDocPr(); + docPr.setId(id); + docPr.setName("Picture " + id); + docPr.setDescr("Generated"); + } + + public void createPicture(XWPFRun run, String blipId, int id, int width, int height) { + final int EMU = 9525; + width *= EMU; + height *= EMU; + CTInline inline = run.getCTR().addNewDrawing().addNewInline(); + + String picXml = "" + + "" + + " " + + " " + + " " + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + ""; + + XmlToken xmlToken = null; + try { + xmlToken = XmlToken.Factory.parse(picXml); + } catch (XmlException xe) { + xe.printStackTrace(); + } + inline.set(xmlToken); + + inline.setDistT(0); + inline.setDistB(0); + inline.setDistL(0); + inline.setDistR(0); + + CTPositiveSize2D extent = inline.addNewExtent(); + extent.setCx(width); + extent.setCy(height); + + CTNonVisualDrawingProps docPr = inline.addNewDocPr(); + docPr.setId(id); + docPr.setName("Picture " + id); + docPr.setDescr("Generated"); + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java index 073c67a..d9ff2ea 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java @@ -9,78 +9,78 @@ package org.jeecgframework.poi.word.entity; */ public class WordImageEntity { - public static String URL = "url"; - public static String Data = "data"; - /** - * 图片输入方式 - */ - private String type = URL; - /** - * 图片宽度 - */ - private int width; - // 图片高度 - private int height; - // 图片地址 - private String url; - // 图片信息 - private byte[] data; - - public WordImageEntity() { - - } - - public WordImageEntity(String url, int width, int height) { - this.url = url; - this.width = width; - this.height = height; - } - - public WordImageEntity(byte[] data, int width, int height) { - this.data = data; - this.width = width; - this.height = height; - this.type = Data; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public byte[] getData() { - return data; - } - - public void setData(byte[] data) { - this.data = data; - } + public static String URL = "url"; + public static String Data = "data"; + /** + * 图片输入方式 + */ + private String type = URL; + /** + * 图片宽度 + */ + private int width; + // 图片高度 + private int height; + // 图片地址 + private String url; + // 图片信息 + private byte[] data; + + public WordImageEntity() { + + } + + public WordImageEntity(byte[] data, int width, int height) { + this.data = data; + this.width = width; + this.height = height; + this.type = Data; + } + + public WordImageEntity(String url, int width, int height) { + this.url = url; + this.width = width; + this.height = height; + } + + public byte[] getData() { + return data; + } + + public int getHeight() { + return height; + } + + public String getType() { + return type; + } + + public String getUrl() { + return url; + } + + public int getWidth() { + return width; + } + + public void setData(byte[] data) { + this.data = data; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setType(String type) { + this.type = type; + } + + public void setUrl(String url) { + this.url = url; + } + + public void setWidth(int width) { + this.width = width; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ExcelListEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ExcelListEntity.java index 4dce013..89bda7e 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ExcelListEntity.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ExcelListEntity.java @@ -13,71 +13,69 @@ import org.jeecgframework.poi.handler.inter.IExcelDataHandler; */ public class ExcelListEntity extends ExcelBaseParams { - public ExcelListEntity() { - - } - - public ExcelListEntity(List list, Class clazz) { - this.list = list; - this.clazz = clazz; - } - - public ExcelListEntity(List list, Class clazz, int headRows) { - this.list = list; - this.clazz = clazz; - this.headRows = headRows; - } - - public ExcelListEntity(List list, Class clazz, - IExcelDataHandler dataHanlder) { - this.list = list; - this.clazz = clazz; - setDataHanlder(dataHanlder); - } - - public ExcelListEntity(List list, Class clazz, - IExcelDataHandler dataHanlder, int headRows) { - this.list = list; - this.clazz = clazz; - this.headRows = headRows; - setDataHanlder(dataHanlder); - } - - /** - * 数据源 - */ - private List list; - /** - * 实体类对象 - */ - private Class clazz; - /** - * 表头行数 - */ - private int headRows = 1; - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Class getClazz() { - return clazz; - } - - public void setClazz(Class clazz) { - this.clazz = clazz; - } - - public int getHeadRows() { - return headRows; - } - - public void setHeadRows(int headRows) { - this.headRows = headRows; - } + /** + * 数据源 + */ + private List list; + + /** + * 实体类对象 + */ + private Class clazz; + + /** + * 表头行数 + */ + private int headRows = 1; + + public ExcelListEntity() { + + } + + public ExcelListEntity(List list, Class clazz) { + this.list = list; + this.clazz = clazz; + } + + public ExcelListEntity(List list, Class clazz, IExcelDataHandler dataHanlder) { + this.list = list; + this.clazz = clazz; + setDataHanlder(dataHanlder); + } + public ExcelListEntity(List list, Class clazz, IExcelDataHandler dataHanlder, int headRows) { + this.list = list; + this.clazz = clazz; + this.headRows = headRows; + setDataHanlder(dataHanlder); + } + public ExcelListEntity(List list, Class clazz, int headRows) { + this.list = list; + this.clazz = clazz; + this.headRows = headRows; + } + + public Class getClazz() { + return clazz; + } + + public int getHeadRows() { + return headRows; + } + + public List getList() { + return list; + } + + public void setClazz(Class clazz) { + this.clazz = clazz; + } + + public void setHeadRows(int headRows) { + this.headRows = headRows; + } + + public void setList(List list) { + this.list = list; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ListParamEntity.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ListParamEntity.java index 890cbd6..8dc22d5 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ListParamEntity.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/params/ListParamEntity.java @@ -7,72 +7,72 @@ package org.jeecgframework.poi.word.entity.params; * @date 2014年7月26日 下午11:14:48 */ public class ListParamEntity { - // 唯一值,在遍历中重复使用 - public static final String SINGLE = "single"; - // 属于数组类型 - public static final String LIST = "list"; - /** - * 属性名称 - */ - private String name; - /** - * 目标 - */ - private String target; - /** - * 当是唯一值的时候直接求出值 - */ - private Object value; - /** - * 数据类型,SINGLE || LIST - */ - private String type; + // 唯一值,在遍历中重复使用 + public static final String SINGLE = "single"; + // 属于数组类型 + public static final String LIST = "list"; + /** + * 属性名称 + */ + private String name; + /** + * 目标 + */ + private String target; + /** + * 当是唯一值的时候直接求出值 + */ + private Object value; + /** + * 数据类型,SINGLE || LIST + */ + private String type; - public ListParamEntity() { + public ListParamEntity() { - } + } - public ListParamEntity(String name, String target) { - this.name = name; - this.target = target; - this.type = LIST; - } - - public ListParamEntity(String name, Object value) { - this.name = name; - this.value = value; - this.type = LIST; - } + public ListParamEntity(String name, Object value) { + this.name = name; + this.value = value; + this.type = LIST; + } - public String getName() { - return name; - } + public ListParamEntity(String name, String target) { + this.name = name; + this.target = target; + this.type = LIST; + } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getTarget() { - return target; - } + public String getTarget() { + return target; + } - public void setTarget(String target) { - this.target = target; - } + public String getType() { + return type; + } - public String getType() { - return type; - } + public Object getValue() { + return value; + } - public void setType(String type) { - this.type = type; - } + public void setName(String name) { + this.name = name; + } - public Object getValue() { - return value; - } + public void setTarget(String target) { + this.target = target; + } - public void setValue(Object value) { - this.value = value; - } + public void setType(String type) { + this.type = type; + } + + public void setValue(Object value) { + this.value = value; + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java index a4c89c0..792edd6 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java @@ -29,245 +29,224 @@ import org.jeecgframework.poi.word.util.ParseWordUtil; @SuppressWarnings({ "unchecked", "rawtypes" }) public class ParseWord07 { - /** - * 解析07版的Word并且进行赋值 - * - * @Author JueYue - * @date 2013-11-16 - * @return - * @throws Exception - */ - public XWPFDocument parseWord(String url, Map map) - throws Exception { - JeecgXWPFDocument doc = WordCache.getXWPFDocumen(url); - parseWordSetValue(doc, map); - return doc; - } - - /** - * 解析07版的Word并且进行赋值 - * - * @Author JueYue - * @date 2013-11-16 - * @return - * @throws Exception - */ - public void parseWord(XWPFDocument document, Map map) - throws Exception { - parseWordSetValue((JeecgXWPFDocument) document, map); - } - - private void parseWordSetValue(JeecgXWPFDocument doc, - Map map) throws Exception { - // 第一步解析文档 - parseAllParagraphic(doc.getParagraphs(), map); - // 第二步解析所有表格 - XWPFTable table; - Iterator itTable = doc.getTablesIterator(); - while (itTable.hasNext()) { - table = itTable.next(); - if (table.getText().indexOf("{{") != -1) { - parseThisTable(table, map); - } - } - - } - - /** - * 解析所有的文本 - * - * @Author JueYue - * @date 2013-11-17 - * @param paragraphs - * @param map - */ - private void parseAllParagraphic(List paragraphs, - Map map) throws Exception { - XWPFParagraph paragraph; - for (int i = 0; i < paragraphs.size(); i++) { - paragraph = paragraphs.get(i); - if (paragraph.getText().indexOf("{{") != -1) { - parseThisParagraph(paragraph, map); - } - - } - - } - - /** - * 解析这个表格 - * - * @Author JueYue - * @date 2013-11-17 - * @param table - * @param map - */ - private void parseThisTable(XWPFTable table, Map map) - throws Exception { - XWPFTableRow row; - List cells; - Object listobj; - ExcelEntityParse excelEntityParse = new ExcelEntityParse(); - for (int i = 0; i < table.getNumberOfRows(); i++) { - row = table.getRow(i); - cells = row.getTableCells(); - if (cells.size() == 1) { - listobj = checkThisTableIsNeedIterator(cells.get(0), map); - if (listobj == null) { - parseThisRow(cells, map); - } else if (listobj instanceof ExcelListEntity) { - table.removeRow(i);// 删除这一行 - excelEntityParse.parseNextRowAndAddRow(table, i, - (ExcelListEntity) listobj); - } else { - table.removeRow(i);// 删除这一行 - ExcelMapParse.parseNextRowAndAddRow(table, i, - (List) listobj); - } - } else { - parseThisRow(cells, map); - } - } - } - - private void parseThisRow(List cells, Map map) - throws Exception { - for (XWPFTableCell cell : cells) { - parseAllParagraphic(cell.getParagraphs(), map); - } - } - - /** - * 判断是不是迭代输出 - * - * @Author JueYue - * @date 2013-11-18 - * @return - * @throws Exception - */ - private Object checkThisTableIsNeedIterator(XWPFTableCell cell, - Map map) throws Exception { - String text = cell.getText().trim(); - // 判断是不是迭代输出 - if (text.startsWith("{{") && text.endsWith("}}") - && text.indexOf("in ") != -1) { - /*text = text.replace("{{", "").replace("}}", "") - .replaceAll("\\s{1,}", " ").trim();*/ - return ParseWordUtil.getRealValue(text.replace("in ", "").trim(), - map); - } - return null; - } - - /** - * 解析这个段落 - * - * @Author JueYue - * @date 2013-11-16 - * @param paragraph - * @param map - */ - private void parseThisParagraph(XWPFParagraph paragraph, - Map map) throws Exception { - XWPFRun run; - XWPFRun currentRun = null;// 拿到的第一个run,用来set值,可以保存格式 - String currentText = "";// 存放当前的text - String text; - Boolean isfinde = false;// 判断是不是已经遇到{{ - List runIndex = new ArrayList();// 存储遇到的run,把他们置空 - for (int i = 0; i < paragraph.getRuns().size(); i++) { - run = paragraph.getRuns().get(i); - text = run.getText(0); - if (text == null || text == "") { - continue; - }// 如果为空或者""这种这继续循环跳过 - if (isfinde) { - currentText += text; - if (currentText.indexOf("{{") == -1) { - isfinde = false; - runIndex.clear(); - } else { - runIndex.add(i); - } - if (currentText.indexOf("}}") != -1) { - changeValues(paragraph, currentRun, currentText, runIndex, - map); - currentText = ""; - isfinde = false; - } - } else if (text.indexOf("{") >= 0) {// 判断是不是开始 - currentText = text; - isfinde = true; - currentRun = run; - } else { - currentText = ""; - } - if (currentText.indexOf("}}") != -1) { - changeValues(paragraph, currentRun, currentText, runIndex, map); - isfinde = false; - } - } - - } - - /** - * 根据条件改变值 - * - * @param map - * @Author JueYue - * @date 2013-11-16 - */ - private void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, - String currentText, List runIndex, Map map) - throws Exception { - Object obj = ParseWordUtil.getRealValue(currentText, map); - if (obj instanceof WordImageEntity) {// 如果是图片就设置为图片 - currentRun.setText("", 0); - addAnImage((WordImageEntity) obj, currentRun); - } else { - currentText = obj.toString(); - currentRun.setText(currentText, 0); - } - for (int k = 0; k < runIndex.size(); k++) { - paragraph.getRuns().get(runIndex.get(k)).setText("", 0); - } - runIndex.clear(); - } - - /** - * 添加图片 - * - * @Author JueYue - * @date 2013-11-20 - * @param obj - * @param currentRun - * @throws Exception - */ - private void addAnImage(WordImageEntity obj, XWPFRun currentRun) - throws Exception { - Object[] isAndType = ParseWordUtil.getIsAndType(obj); - String picId; - try { - picId = currentRun - .getParagraph() - .getDocument() - .addPictureData((byte[]) isAndType[0], - (Integer) isAndType[1]); - ((JeecgXWPFDocument) currentRun.getParagraph().getDocument()) - .createPicture( - currentRun, - picId, - currentRun - .getParagraph() - .getDocument() - .getNextPicNameNumber( - (Integer) isAndType[1]), - obj.getWidth(), obj.getHeight()); - - } catch (Exception e) { - e.printStackTrace(); - } - - } + /** + * 添加图片 + * + * @Author JueYue + * @date 2013-11-20 + * @param obj + * @param currentRun + * @throws Exception + */ + private void addAnImage(WordImageEntity obj, XWPFRun currentRun) throws Exception { + Object[] isAndType = ParseWordUtil.getIsAndType(obj); + String picId; + try { + picId = currentRun.getParagraph().getDocument() + .addPictureData((byte[]) isAndType[0], (Integer) isAndType[1]); + ((JeecgXWPFDocument) currentRun.getParagraph().getDocument()).createPicture(currentRun, + picId, + currentRun.getParagraph().getDocument() + .getNextPicNameNumber((Integer) isAndType[1]), obj.getWidth(), obj.getHeight()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * 根据条件改变值 + * + * @param map + * @Author JueYue + * @date 2013-11-16 + */ + private void changeValues(XWPFParagraph paragraph, XWPFRun currentRun, String currentText, + List runIndex, Map map) throws Exception { + Object obj = ParseWordUtil.getRealValue(currentText, map); + if (obj instanceof WordImageEntity) {// 如果是图片就设置为图片 + currentRun.setText("", 0); + addAnImage((WordImageEntity) obj, currentRun); + } else { + currentText = obj.toString(); + currentRun.setText(currentText, 0); + } + for (int k = 0; k < runIndex.size(); k++) { + paragraph.getRuns().get(runIndex.get(k)).setText("", 0); + } + runIndex.clear(); + } + + /** + * 判断是不是迭代输出 + * + * @Author JueYue + * @date 2013-11-18 + * @return + * @throws Exception + */ + private Object checkThisTableIsNeedIterator(XWPFTableCell cell, Map map) + throws Exception { + String text = cell.getText().trim(); + // 判断是不是迭代输出 + if (text.startsWith("{{") && text.endsWith("}}") && text.indexOf("in ") != -1) { + /*text = text.replace("{{", "").replace("}}", "") + .replaceAll("\\s{1,}", " ").trim();*/ + return ParseWordUtil.getRealValue(text.replace("in ", "").trim(), map); + } + return null; + } + + /** + * 解析所有的文本 + * + * @Author JueYue + * @date 2013-11-17 + * @param paragraphs + * @param map + */ + private void parseAllParagraphic(List paragraphs, Map map) + throws Exception { + XWPFParagraph paragraph; + for (int i = 0; i < paragraphs.size(); i++) { + paragraph = paragraphs.get(i); + if (paragraph.getText().indexOf("{{") != -1) { + parseThisParagraph(paragraph, map); + } + + } + + } + + /** + * 解析这个段落 + * + * @Author JueYue + * @date 2013-11-16 + * @param paragraph + * @param map + */ + private void parseThisParagraph(XWPFParagraph paragraph, Map map) + throws Exception { + XWPFRun run; + XWPFRun currentRun = null;// 拿到的第一个run,用来set值,可以保存格式 + String currentText = "";// 存放当前的text + String text; + Boolean isfinde = false;// 判断是不是已经遇到{{ + List runIndex = new ArrayList();// 存储遇到的run,把他们置空 + for (int i = 0; i < paragraph.getRuns().size(); i++) { + run = paragraph.getRuns().get(i); + text = run.getText(0); + if (text == null || text == "") { + continue; + }// 如果为空或者""这种这继续循环跳过 + if (isfinde) { + currentText += text; + if (currentText.indexOf("{{") == -1) { + isfinde = false; + runIndex.clear(); + } else { + runIndex.add(i); + } + if (currentText.indexOf("}}") != -1) { + changeValues(paragraph, currentRun, currentText, runIndex, map); + currentText = ""; + isfinde = false; + } + } else if (text.indexOf("{") >= 0) {// 判断是不是开始 + currentText = text; + isfinde = true; + currentRun = run; + } else { + currentText = ""; + } + if (currentText.indexOf("}}") != -1) { + changeValues(paragraph, currentRun, currentText, runIndex, map); + isfinde = false; + } + } + + } + + private void parseThisRow(List cells, Map map) throws Exception { + for (XWPFTableCell cell : cells) { + parseAllParagraphic(cell.getParagraphs(), map); + } + } + + /** + * 解析这个表格 + * + * @Author JueYue + * @date 2013-11-17 + * @param table + * @param map + */ + private void parseThisTable(XWPFTable table, Map map) throws Exception { + XWPFTableRow row; + List cells; + Object listobj; + ExcelEntityParse excelEntityParse = new ExcelEntityParse(); + for (int i = 0; i < table.getNumberOfRows(); i++) { + row = table.getRow(i); + cells = row.getTableCells(); + if (cells.size() == 1) { + listobj = checkThisTableIsNeedIterator(cells.get(0), map); + if (listobj == null) { + parseThisRow(cells, map); + } else if (listobj instanceof ExcelListEntity) { + table.removeRow(i);// 删除这一行 + excelEntityParse.parseNextRowAndAddRow(table, i, (ExcelListEntity) listobj); + } else { + table.removeRow(i);// 删除这一行 + ExcelMapParse.parseNextRowAndAddRow(table, i, (List) listobj); + } + } else { + parseThisRow(cells, map); + } + } + } + + /** + * 解析07版的Word并且进行赋值 + * + * @Author JueYue + * @date 2013-11-16 + * @return + * @throws Exception + */ + public XWPFDocument parseWord(String url, Map map) throws Exception { + JeecgXWPFDocument doc = WordCache.getXWPFDocumen(url); + parseWordSetValue(doc, map); + return doc; + } + + /** + * 解析07版的Word并且进行赋值 + * + * @Author JueYue + * @date 2013-11-16 + * @return + * @throws Exception + */ + public void parseWord(XWPFDocument document, Map map) throws Exception { + parseWordSetValue((JeecgXWPFDocument) document, map); + } + + private void parseWordSetValue(JeecgXWPFDocument doc, Map map) throws Exception { + // 第一步解析文档 + parseAllParagraphic(doc.getParagraphs(), map); + // 第二步解析所有表格 + XWPFTable table; + Iterator itTable = doc.getTablesIterator(); + while (itTable.hasNext()) { + table = itTable.next(); + if (table.getText().indexOf("{{") != -1) { + parseThisTable(table, map); + } + } + + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelEntityParse.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelEntityParse.java index b8bc905..56fc3c7 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelEntityParse.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelEntityParse.java @@ -28,186 +28,173 @@ import org.jeecgframework.poi.word.entity.params.ExcelListEntity; */ public class ExcelEntityParse extends ExportBase { - /** - * 解析上一行并生成更多行 - * - * @param table - * @param i - * @param listobj - */ - public void parseNextRowAndAddRow(XWPFTable table, int index, - ExcelListEntity entity) { - checkExcelParams(entity); - // 获取表头数据 - Map titlemap = getTitleMap(table, index, - entity.getHeadRows()); - try { - // 得到所有字段 - Field fileds[] = POIPublicUtil.getClassFields(entity.getClazz()); - ExcelTarget etarget = entity.getClazz().getAnnotation( - ExcelTarget.class); - String targetId = null; - if (etarget != null) { - targetId = etarget.value(); - } - // 获取实体对象的导出数据 - List excelParams = new ArrayList(); - getAllExcelField(null, targetId, fileds, excelParams, - entity.getClazz(), null); - // 根据表头进行筛选排序 - sortAndFilterExportField(excelParams, titlemap); - short rowHeight = getRowHeight(excelParams); - Iterator its = entity.getList().iterator(); - while (its.hasNext()) { - Object t = its.next(); - index += createCells(index, t, excelParams, table, rowHeight); - } - } catch (Exception e) { - e.printStackTrace(); - } - } + private static void checkExcelParams(ExcelListEntity entity) { + if (entity.getList() == null || entity.getClazz() == null) { + throw new WordExportException(WordExportEnum.EXCEL_PARAMS_ERROR); + } - private int createCells(int index, Object t, - List excelParams, XWPFTable table, - short rowHeight) throws Exception { - ExcelExportEntity entity; - XWPFTableRow row = table.createRow(); - 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(index + listC, cellNum, obj, - entity.getList(), table); - listC++; - } - cellNum += entity.getList().size(); - if (list != null && list.size() > maxHeight) { - maxHeight = list.size(); - } - } else { - Object value = getCellValue(entity, t); - if (entity.getType() == 1) { - setCellValue(row, value, cellNum++); - } - } - } - // 合并需要合并的单元格 - 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()) { - table.setCellMargins(index, index + maxHeight - 1, cellNum, - cellNum); - cellNum++; - } - } - return maxHeight; - } + } - /** - * 创建List之后的各个Cells - * - * @param styles - */ - public void createListCells(int index, int cellNum, Object obj, - List excelParams, XWPFTable table) - throws Exception { - ExcelExportEntity entity; - XWPFTableRow row; - if (table.getRow(index) == null) { - row = table.createRow(); - row.setHeight(getRowHeight(excelParams)); - } else { - row = table.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) { - setCellValue(row, value, cellNum++); - } - } - } + private int createCells(int index, Object t, List excelParams, + XWPFTable table, short rowHeight) throws Exception { + ExcelExportEntity entity; + XWPFTableRow row = table.createRow(); + 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(index + listC, cellNum, obj, entity.getList(), table); + listC++; + } + cellNum += entity.getList().size(); + if (list != null && list.size() > maxHeight) { + maxHeight = list.size(); + } + } else { + Object value = getCellValue(entity, t); + if (entity.getType() == 1) { + setCellValue(row, value, cellNum++); + } + } + } + // 合并需要合并的单元格 + 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()) { + table.setCellMargins(index, index + maxHeight - 1, cellNum, cellNum); + cellNum++; + } + } + return maxHeight; + } - private void setCellValue(XWPFTableRow row, Object value, int cellNum) { - if (row.getCell(cellNum++) != null) { - row.getCell(cellNum - 1).setText( - value == null ? "" : value.toString()); - } else { - row.createCell().setText(value == null ? "" : value.toString()); - } - } + /** + * 创建List之后的各个Cells + * + * @param styles + */ + public void createListCells(int index, int cellNum, Object obj, + List excelParams, XWPFTable table) + throws Exception { + ExcelExportEntity entity; + XWPFTableRow row; + if (table.getRow(index) == null) { + row = table.createRow(); + row.setHeight(getRowHeight(excelParams)); + } else { + row = table.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) { + setCellValue(row, value, cellNum++); + } + } + } - /** - * 对导出序列进行排序和塞选 - * - * @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 table + * @param index + * @return + */ + private Map getTitleMap(XWPFTable table, int index, int headRows) { + if (index < headRows) { + throw new WordExportException(WordExportEnum.EXCEL_NO_HEAD); + } + Map map = new HashMap(); + String text; + for (int j = 0; j < headRows; j++) { + List cells = table.getRow(index - j - 1).getTableCells(); + for (int i = 0; i < cells.size(); i++) { + text = cells.get(i).getText(); + if (StringUtils.isEmpty(text)) { + throw new WordExportException(WordExportEnum.EXCEL_HEAD_HAVA_NULL); + } + map.put(text, i); + } + } + return map; + } - /** - * 获取表头数据 - * - * @param table - * @param index - * @return - */ - private Map getTitleMap(XWPFTable table, int index, - int headRows) { - if (index < headRows) { - throw new WordExportException(WordExportEnum.EXCEL_NO_HEAD); - } - Map map = new HashMap(); - String text; - for (int j = 0; j < headRows; j++) { - List cells = table.getRow(index - j - 1) - .getTableCells(); - for (int i = 0; i < cells.size(); i++) { - text = cells.get(i).getText(); - if (StringUtils.isEmpty(text)) { - throw new WordExportException( - WordExportEnum.EXCEL_HEAD_HAVA_NULL); - } - map.put(text, i); - } - } - return map; - } + /** + * 解析上一行并生成更多行 + * + * @param table + * @param i + * @param listobj + */ + public void parseNextRowAndAddRow(XWPFTable table, int index, ExcelListEntity entity) { + checkExcelParams(entity); + // 获取表头数据 + Map titlemap = getTitleMap(table, index, entity.getHeadRows()); + try { + // 得到所有字段 + Field fileds[] = POIPublicUtil.getClassFields(entity.getClazz()); + ExcelTarget etarget = entity.getClazz().getAnnotation(ExcelTarget.class); + String targetId = null; + if (etarget != null) { + targetId = etarget.value(); + } + // 获取实体对象的导出数据 + List excelParams = new ArrayList(); + getAllExcelField(null, targetId, fileds, excelParams, entity.getClazz(), null); + // 根据表头进行筛选排序 + sortAndFilterExportField(excelParams, titlemap); + short rowHeight = getRowHeight(excelParams); + Iterator its = entity.getList().iterator(); + while (its.hasNext()) { + Object t = its.next(); + index += createCells(index, t, excelParams, table, rowHeight); + } + } catch (Exception e) { + e.printStackTrace(); + } + } - private static void checkExcelParams(ExcelListEntity entity) { - if (entity.getList() == null || entity.getClazz() == null) { - throw new WordExportException(WordExportEnum.EXCEL_PARAMS_ERROR); - } + private void setCellValue(XWPFTableRow row, Object value, int cellNum) { + if (row.getCell(cellNum++) != null) { + row.getCell(cellNum - 1).setText(value == null ? "" : value.toString()); + } else { + row.createCell().setText(value == null ? "" : value.toString()); + } + } - } + /** + * 对导出序列进行排序和塞选 + * + * @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); + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelMapParse.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelMapParse.java index 961fd9c..5594386 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelMapParse.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/excel/ExcelMapParse.java @@ -13,59 +13,57 @@ import org.jeecgframework.poi.word.util.ParseWordUtil; * @date 2014年8月9日 下午10:28:46 */ public final class ExcelMapParse { - - /** - * 解析下一行,并且生成更多的行 - * - * @Author JueYue - * @date 2013-11-18 - * @param table - * @param listobj2 - */ - public static void parseNextRowAndAddRow(XWPFTable table, int index, - List list) throws Exception { - XWPFTableRow currentRow = table.getRow(index); - String[] params = parseCurrentRowGetParams(currentRow); - table.removeRow(index);// 移除这一行 - int cellIndex = 0;// 创建完成对象一行好像多了一个cell - for (Object obj : list) { - currentRow = table.createRow(); - for (cellIndex = 0; cellIndex < currentRow.getTableCells().size(); cellIndex++) { - currentRow - .getTableCells() - .get(cellIndex) - .setText( - ParseWordUtil.getValueDoWhile(obj, - params[cellIndex].split("\\."), 0) - .toString()); - } - for (; cellIndex < params.length; cellIndex++) { - currentRow.createCell().setText( - ParseWordUtil.getValueDoWhile(obj, - params[cellIndex].split("\\."), 0).toString()); - } - } - } - - /** - * 解析参数行,获取参数列表 - * - * @Author JueYue - * @date 2013-11-18 - * @param currentRow - * @return - */ - private static String[] parseCurrentRowGetParams(XWPFTableRow currentRow) { - List cells = currentRow.getTableCells(); - String[] params = new String[cells.size()]; - String text; - for (int i = 0; i < cells.size(); i++) { - text = cells.get(i).getText(); - params[i] = text == null ? "" : text.trim().replace("{{", "") - .replace("}}", ""); - } - return params; - } + /** + * 解析参数行,获取参数列表 + * + * @Author JueYue + * @date 2013-11-18 + * @param currentRow + * @return + */ + private static String[] parseCurrentRowGetParams(XWPFTableRow currentRow) { + List cells = currentRow.getTableCells(); + String[] params = new String[cells.size()]; + String text; + for (int i = 0; i < cells.size(); i++) { + text = cells.get(i).getText(); + params[i] = text == null ? "" : text.trim().replace("{{", "").replace("}}", ""); + } + return params; + } + + /** + * 解析下一行,并且生成更多的行 + * + * @Author JueYue + * @date 2013-11-18 + * @param table + * @param listobj2 + */ + public static void parseNextRowAndAddRow(XWPFTable table, int index, List list) + throws Exception { + XWPFTableRow currentRow = table.getRow(index); + String[] params = parseCurrentRowGetParams(currentRow); + table.removeRow(index);// 移除这一行 + int cellIndex = 0;// 创建完成对象一行好像多了一个cell + for (Object obj : list) { + currentRow = table.createRow(); + for (cellIndex = 0; cellIndex < currentRow.getTableCells().size(); cellIndex++) { + currentRow + .getTableCells() + .get(cellIndex) + .setText( + ParseWordUtil.getValueDoWhile(obj, params[cellIndex].split("\\."), 0) + .toString()); + } + for (; cellIndex < params.length; cellIndex++) { + currentRow.createCell().setText( + ParseWordUtil.getValueDoWhile(obj, params[cellIndex].split("\\."), 0) + .toString()); + } + } + + } } diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java index 089bfd1..55ae9ee 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java @@ -14,7 +14,6 @@ import org.jeecgframework.poi.util.POIPublicUtil; import org.jeecgframework.poi.word.entity.WordImageEntity; import org.jeecgframework.poi.word.entity.params.ExcelListEntity; - /** * 解析公告类 * Excel 实体注解,暂时不支持图片 @@ -23,123 +22,125 @@ import org.jeecgframework.poi.word.entity.params.ExcelListEntity; * @version 1.1 */ public class ParseWordUtil { - - /** - * 解析数据 - * - * @Author JueYue - * @date 2013-11-16 - * @return - */ - public static Object getRealValue(String currentText, - Map map) throws Exception { - String params = ""; - while (currentText.indexOf("{{") != -1) { - params = currentText.substring(currentText.indexOf("{{") + 2, - currentText.indexOf("}}")); - Object obj = getParamsValue(params.trim(),map); - //判断图片或者是集合 - if(obj instanceof WordImageEntity||obj instanceof List ||obj instanceof ExcelListEntity){ - return obj; - }else{ - currentText = currentText.replace("{{" + params + "}}", - obj.toString()); - } - } - return currentText; - } - /** - * 获取参数值 - * - * @param params - * @param map - * @return - */ - private static Object 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) : ""; - } + private static Integer getImageType(String type) { + if (type.equalsIgnoreCase("JPG") || type.equalsIgnoreCase("JPEG")) { + return XWPFDocument.PICTURE_TYPE_JPEG; + } + if (type.equalsIgnoreCase("GIF")) { + return XWPFDocument.PICTURE_TYPE_GIF; + } + if (type.equalsIgnoreCase("BMP")) { + return XWPFDocument.PICTURE_TYPE_GIF; + } + if (type.equalsIgnoreCase("PNG")) { + return XWPFDocument.PICTURE_TYPE_PNG; + } + return XWPFDocument.PICTURE_TYPE_JPEG; + } + + /** + * 返回流和图片类型 + *@Author JueYue + *@date 2013-11-20 + *@param obj + *@return (byte[]) isAndType[0],(Integer)isAndType[1] + * @throws Exception + */ + public static Object[] getIsAndType(WordImageEntity entity) throws Exception { + Object[] result = new Object[2]; + String type; + if (entity.getType().equals(WordImageEntity.URL)) { + ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); + BufferedImage bufferImg; + String path = Thread.currentThread().getContextClassLoader().getResource("").toURI() + .getPath() + + entity.getUrl(); + path = path.replace("WEB-INF/classes/", ""); + path = path.replace("file:/", ""); + bufferImg = ImageIO.read(new File(path)); + ImageIO.write( + bufferImg, + entity.getUrl().substring(entity.getUrl().indexOf(".") + 1, + entity.getUrl().length()), byteArrayOut); + result[0] = byteArrayOut.toByteArray(); + type = entity.getUrl().split("/.")[entity.getUrl().split("/.").length - 1]; + } else { + result[0] = entity.getData(); + type = POIPublicUtil.getFileExtendName(entity.getData()); + } + result[1] = getImageType(type); + return result; + } + + /** + * 获取参数值 + * + * @param params + * @param map + * @return + */ + private static Object 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) : ""; + } - /** - * 通过遍历过去对象值 - * - * @param object - * @param paramsArr - * @param index - * @return - * @throws Exception - * @throws InvocationTargetException - * @throws IllegalAccessException - * @throws IllegalArgumentException - */ - @SuppressWarnings("rawtypes") - public static Object getValueDoWhile(Object object, String[] paramsArr, - int index) throws Exception{ - if (object == null) { - return ""; - } - if(object instanceof WordImageEntity){ - return object; - } - if (object instanceof Map) { - object = ((Map) object).get(paramsArr[index]); - } else { - object = POIPublicUtil.getMethod(paramsArr[index], - object.getClass()).invoke(object, new Object[] {}); - } - return (index == paramsArr.length - 1) ? (object == null ? "" : object) - : getValueDoWhile(object, paramsArr, ++index); - } - - /** - * 返回流和图片类型 - *@Author JueYue - *@date 2013-11-20 - *@param obj - *@return (byte[]) isAndType[0],(Integer)isAndType[1] - * @throws Exception - */ - public static Object[] getIsAndType(WordImageEntity entity) throws Exception { - Object[] result = new Object[2]; - String type; - if(entity.getType().equals(WordImageEntity.URL)){ - ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); - BufferedImage bufferImg; - String path = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath() +entity.getUrl(); - path = path.replace("WEB-INF/classes/",""); - path = path.replace("file:/",""); - bufferImg = ImageIO.read( - new File(path)); - ImageIO.write(bufferImg,entity.getUrl().substring(entity.getUrl().indexOf(".")+1,entity.getUrl().length()),byteArrayOut); - result[0] = byteArrayOut.toByteArray(); - type = entity.getUrl().split("/.")[ entity.getUrl().split("/.").length-1]; - }else{ - result[0] = entity.getData(); - type = POIPublicUtil.getFileExtendName(entity.getData()); - } - result[1] = getImageType(type); - return result; - } - - private static Integer getImageType(String type) { - if(type.equalsIgnoreCase("JPG")||type.equalsIgnoreCase("JPEG")){ - return XWPFDocument.PICTURE_TYPE_JPEG; - } - if(type.equalsIgnoreCase("GIF")){ - return XWPFDocument.PICTURE_TYPE_GIF; - } - if(type.equalsIgnoreCase("BMP")){ - return XWPFDocument.PICTURE_TYPE_GIF; - } - if(type.equalsIgnoreCase("PNG")){ - return XWPFDocument.PICTURE_TYPE_PNG; - } - return XWPFDocument.PICTURE_TYPE_JPEG; - } + /** + * 解析数据 + * + * @Author JueYue + * @date 2013-11-16 + * @return + */ + public static Object getRealValue(String currentText, Map map) throws Exception { + String params = ""; + while (currentText.indexOf("{{") != -1) { + params = currentText + .substring(currentText.indexOf("{{") + 2, currentText.indexOf("}}")); + Object obj = getParamsValue(params.trim(), map); + //判断图片或者是集合 + if (obj instanceof WordImageEntity || obj instanceof List + || obj instanceof ExcelListEntity) { + return obj; + } else { + currentText = currentText.replace("{{" + params + "}}", obj.toString()); + } + } + return currentText; + } + /** + * 通过遍历过去对象值 + * + * @param object + * @param paramsArr + * @param index + * @return + * @throws Exception + * @throws InvocationTargetException + * @throws IllegalAccessException + * @throws IllegalArgumentException + */ + @SuppressWarnings("rawtypes") + public static Object getValueDoWhile(Object object, String[] paramsArr, int index) + throws Exception { + if (object == null) { + return ""; + } + if (object instanceof WordImageEntity) { + return object; + } + if (object instanceof Map) { + object = ((Map) object).get(paramsArr[index]); + } else { + object = POIPublicUtil.getMethod(paramsArr[index], object.getClass()).invoke(object, + new Object[] {}); + } + return (index == paramsArr.length - 1) ? (object == null ? "" : object) : getValueDoWhile( + object, paramsArr, ++index); + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/UtilTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/UtilTest.java index f6e1a7b..ae2b251 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/UtilTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/UtilTest.java @@ -1,13 +1,12 @@ package org.jeecgframework.poi; public class UtilTest { - - - public static void main(String[] args) { - String text = " {{ p in pList}}"; - text = text.replace("{{", "").replace("}}", "").replaceAll("\\s{1,}", " ").trim(); - System.out.println(text); - System.out.println(text.length()); - } + + public static void main(String[] args) { + String text = " {{ p in pList}}"; + text = text.replace("{{", "").replace("}}", "").replaceAll("\\s{1,}", " ").trim(); + System.out.println(text); + System.out.println(text.length()); + } } 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 index 92e9a97..ee5209e 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/CourseEntity.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/CourseEntity.java @@ -19,90 +19,90 @@ import org.jeecgframework.poi.excel.annotation.ExcelVerify; @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; + /** 主键 */ + 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; + @ExcelCollection(name = "选课学生", orderNum = "4") + private List students; - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 主键 - */ + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 主键 + */ - public String getId() { - return this.id; - } + 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 - * - * @return: java.lang.String 课程名称 - */ - public String getName() { - return this.name; - } + public TeacherEntity getShuxueteacher() { + return shuxueteacher; + } - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String 课程名称 - */ - public void setName(String name) { - this.name = name; - } + public List getStudents() { + return students; + } - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 老师主键 - */ - public TeacherEntity getTeacher() { - return teacher; - } + /** + * 方法: 取得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; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 主键 + */ + public void setId(String id) { + this.id = id; + } - public List getStudents() { - return students; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 课程名称 + */ + public void setName(String name) { + this.name = name; + } - public void setStudents(List students) { - this.students = students; - } + public void setShuxueteacher(TeacherEntity shuxueteacher) { + this.shuxueteacher = shuxueteacher; + } - public TeacherEntity getShuxueteacher() { - return shuxueteacher; - } + public void setStudents(List students) { + this.students = students; + } - public void setShuxueteacher(TeacherEntity shuxueteacher) { - this.shuxueteacher = shuxueteacher; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 老师主键 + */ + public void setTeacher(TeacherEntity teacher) { + this.teacher = teacher; + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClient.java b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClient.java index 563b6e2..7c54590 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClient.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClient.java @@ -2,7 +2,6 @@ package org.jeecgframework.poi.entity; import java.util.Date; - import org.jeecgframework.poi.excel.annotation.Excel; import org.jeecgframework.poi.excel.annotation.ExcelEntity; @@ -16,131 +15,132 @@ import org.jeecgframework.poi.excel.annotation.ExcelEntity; */ @SuppressWarnings("serial") public class MsgClient implements java.io.Serializable { - /** id */ - private java.lang.String id; - // 电话号码(主键) - @Excel(name = "电话号码") - private String clientPhone = null; - // 客户姓名 - @Excel(name = "姓名") - private String clientName = null; - // 所属分组 - @ExcelEntity - private MsgClientGroup group = null; - // 备注 - @Excel(name = "备注") - private String remark = null; - // 生日 - @Excel(name = "出生日期") - private Date birthday = null; - // 创建人 - private String createBy = null; - - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String id - */ - - public java.lang.String getId() { - return this.id; - } - - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String id - */ - public void setId(java.lang.String id) { - this.id = id; - } - - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 电话号码 - */ - public java.lang.String getClientPhone() { - return this.clientPhone; - } - - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String 电话号码 - */ - public void setClientPhone(java.lang.String clientPhone) { - this.clientPhone = clientPhone; - } - - public MsgClientGroup getGroup() { - return group; - } - - public void setGroup(MsgClientGroup group) { - this.group = group; - } - - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 客户姓名 - */ - public java.lang.String getClientName() { - return this.clientName; - } - - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String 客户姓名 - */ - public void setClientName(java.lang.String clientName) { - this.clientName = clientName; - } - - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 备注 - */ - public java.lang.String getRemark() { - return this.remark; - } - - /** - * 方法: 设置java.lang.String - * - * @param remark - * - * @param: java.lang.String 备注 - */ - public void setRemark(java.lang.String remark) { - this.remark = remark; - } - - /** - * 方法: 取得java.util.Date - * - * @return: java.util.Date 生日 - */ - public java.util.Date getBirthday() { - return this.birthday; - } - - /** - * 方法: 设置java.util.Date - * - * @param: java.util.Date 生日 - */ - public void setBirthday(java.util.Date birthday) { - this.birthday = birthday; - } - public String getCreateBy() { - return createBy; - } - - public void setCreateBy(String createBy) { - this.createBy = createBy; - } + /** id */ + private java.lang.String id; + // 电话号码(主键) + @Excel(name = "电话号码") + private String clientPhone = null; + // 客户姓名 + @Excel(name = "姓名") + private String clientName = null; + // 所属分组 + @ExcelEntity + private MsgClientGroup group = null; + // 备注 + @Excel(name = "备注") + private String remark = null; + // 生日 + @Excel(name = "出生日期") + private Date birthday = null; + // 创建人 + private String createBy = null; + + /** + * 方法: 取得java.util.Date + * + * @return: java.util.Date 生日 + */ + public java.util.Date getBirthday() { + return this.birthday; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 客户姓名 + */ + public java.lang.String getClientName() { + return this.clientName; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 电话号码 + */ + public java.lang.String getClientPhone() { + return this.clientPhone; + } + + public String getCreateBy() { + return createBy; + } + + public MsgClientGroup getGroup() { + return group; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String id + */ + + public java.lang.String getId() { + return this.id; + } + + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 备注 + */ + public java.lang.String getRemark() { + return this.remark; + } + + /** + * 方法: 设置java.util.Date + * + * @param: java.util.Date 生日 + */ + public void setBirthday(java.util.Date birthday) { + this.birthday = birthday; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 客户姓名 + */ + public void setClientName(java.lang.String clientName) { + this.clientName = clientName; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 电话号码 + */ + public void setClientPhone(java.lang.String clientPhone) { + this.clientPhone = clientPhone; + } + + public void setCreateBy(String createBy) { + this.createBy = createBy; + } + + public void setGroup(MsgClientGroup group) { + this.group = group; + } + + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String id + */ + public void setId(java.lang.String id) { + this.id = id; + } + + /** + * 方法: 设置java.lang.String + * + * @param remark + * + * @param: java.lang.String 备注 + */ + public void setRemark(java.lang.String remark) { + this.remark = remark; + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClientGroup.java b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClientGroup.java index 21d8a35..e153846 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClientGroup.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/MsgClientGroup.java @@ -1,57 +1,55 @@ package org.jeecgframework.poi.entity; import java.io.Serializable; -import java.util.List; - import org.jeecgframework.poi.excel.annotation.Excel; - /** * 客户分组表 * * @author yjl * */ -public class MsgClientGroup implements Serializable{ - - - /** - * - */ - private static final long serialVersionUID = 6946265640897464878L; - - // 组名 - @Excel(name ="分组") - private String groupName = null; - /** - * 创建人 - */ - private String createBy; - - // 一个组下 可能存在N多客户 - //private List clients = null; - - public String getGroupName() { - return groupName; - } - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - /*@org.codehaus.jackson.annotate.JsonIgnore - @OneToMany(cascade = CascadeType.REMOVE,fetch = FetchType.LAZY,mappedBy = "group") - public List getClients() { - return clients; - } - - public void setClients(List clients) { - this.clients = clients; - }*/ - public String getCreateBy() { - return createBy; - } - public void setCreateBy(String createBy) { - this.createBy = createBy; - } +public class MsgClientGroup implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6946265640897464878L; + + // 组名 + @Excel(name = "分组") + private String groupName = null; + /** + * 创建人 + */ + private String createBy; + + // 一个组下 可能存在N多客户 + //private List clients = null; + + /*@org.codehaus.jackson.annotate.JsonIgnore + @OneToMany(cascade = CascadeType.REMOVE,fetch = FetchType.LAZY,mappedBy = "group") + public List getClients() { + return clients; + } + + public void setClients(List clients) { + this.clients = clients; + }*/ + public String getCreateBy() { + return createBy; + } + + public String getGroupName() { + return groupName; + } + + public void setCreateBy(String createBy) { + this.createBy = createBy; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } } 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 index b8667d4..897bd75 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/StudentEntity.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/StudentEntity.java @@ -1,9 +1,9 @@ package org.jeecgframework.poi.entity; -import org.jeecgframework.poi.excel.annotation.Excel; - import java.util.Date; +import org.jeecgframework.poi.excel.annotation.Excel; + /** * @author jueyue * @version V1.0 @@ -13,95 +13,95 @@ import java.util.Date; */ @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; + /** + * 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; + @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; - } + public Date getBirthday() { + return birthday; + } - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String id - */ - public void setId(String id) { - this.id = id; - } + public CourseEntity getCourse() { + return course; + } - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 学生姓名 - */ - public String getName() { - return this.name; - } + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String id + */ + public String getId() { + return this.id; + } - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String 学生姓名 - */ - public void setName(String name) { - this.name = name; - } + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String 学生姓名 + */ + public String getName() { + return this.name; + } - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String 学生性别 - */ - public int getSex() { - return this.sex; - } + /** + * 方法: 取得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 void setBirthday(Date birthday) { + this.birthday = birthday; + } - public CourseEntity getCourse() { - return course; - } + public void setCourse(CourseEntity course) { + this.course = course; + } - public void setCourse(CourseEntity course) { - this.course = course; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String id + */ + public void setId(String id) { + this.id = id; + } - public Date getBirthday() { - return birthday; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 学生姓名 + */ + public void setName(String name) { + this.name = name; + } - public void setBirthday(Date birthday) { - this.birthday = birthday; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String 学生性别 + */ + public void setSex(int sex) { + this.sex = sex; + } } 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 index 58613ed..7f0a6d8 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/entity/TeacherEntity.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/entity/TeacherEntity.java @@ -14,59 +14,59 @@ import org.jeecgframework.poi.excel.annotation.ExcelTarget; @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; + /** 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; - */ + /* + * @Excel(exportName="老师照片",orderNum="3",exportType=2,exportFieldHeight=15, + * exportFieldWidth=20) private String pic; + */ - /** - * 方法: 取得java.lang.String - * - * @return: java.lang.String id - */ + /** + * 方法: 取得java.lang.String + * + * @return: java.lang.String id + */ - public String getId() { - return this.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 - * - * @return: java.lang.String name - */ - public String getName() { - return this.name; - } + /** + * 方法: 设置java.lang.String + * + * @param: java.lang.String id + */ + public void setId(String id) { + this.id = id; + } - /** - * 方法: 设置java.lang.String - * - * @param: java.lang.String name - */ - public void setName(String name) { - this.name = 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; } - */ + /* + * 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 index 35a49a8..0c5f0ba 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtilTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/ExcelImportUtilTest.java @@ -1,32 +1,26 @@ package org.jeecgframework.poi.excel; -import static org.junit.Assert.*; - import java.io.File; -import java.util.Collection; import java.util.Date; import java.util.List; import org.jeecgframework.poi.entity.CourseEntity; -import org.jeecgframework.poi.entity.MsgClient; -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); - //params.setSheetNum(9); - params.setNeedSave(true); - long start = new Date().getTime(); - List list = ExcelImportUtil.importExcel(new File( - "d:/tt.xls"), CourseEntity.class, params); - System.out.println(list.size() + "-----" - + (new Date().getTime() - start)); - } + @Test + public void test() { + ImportParams params = new ImportParams(); + params.setTitleRows(2); + params.setHeadRows(2); + //params.setSheetNum(9); + params.setNeedSave(true); + long start = new Date().getTime(); + List list = ExcelImportUtil.importExcel(new File("d:/tt.xls"), + CourseEntity.class, params); + System.out.println(list.size() + "-----" + (new Date().getTime() - start)); + } } 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 index 7665fe0..63d14e4 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/MyExcelExport.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/MyExcelExport.java @@ -10,34 +10,29 @@ 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); - } - - + @Override + public HSSFCellStyle getHeaderStyle(HSSFWorkbook workbook, ExportParams entity) { + return super.getHeaderStyle(workbook, entity); + } + + @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); + } + + @Override + public HSSFCellStyle getTitleStyle(HSSFWorkbook workbook, ExportParams entity) { + return super.getTitleStyle(workbook, entity); + } + + @Override + public HSSFCellStyle getTwoStyle(HSSFWorkbook workbook, boolean isWarp) { + return super.getTwoStyle(workbook, isWarp); + } } 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 index 0a5d96b..8a12ffa 100644 --- 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 @@ -4,19 +4,17 @@ 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 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); - } - - + @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/ExcelExportForMap.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportForMap.java index 43af4b3..1a36c1c 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportForMap.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportForMap.java @@ -1,13 +1,5 @@ package org.jeecgframework.poi.excel.test; -import static org.junit.Assert.*; - -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -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.params.ExcelExportEntity; - import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; @@ -16,36 +8,40 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.jeecgframework.poi.excel.ExcelExportUtil; +import org.jeecgframework.poi.excel.entity.ExportParams; +import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; import org.junit.Test; public class ExcelExportForMap { - @Test - public void test() { - try { - List entity = new ArrayList(); - entity.add(new ExcelExportEntity("姓名", "name")); - entity.add(new ExcelExportEntity("性别", "sex")); - - List> list = new ArrayList>(); - Map map; - for (int i = 0; i < 10; i++) { - map = new HashMap(); - map.put("name", "1" + i); - map.put("sex", "2" + i); - list.add(map); - } - - HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams( - "测试", "测试"), entity, list); - FileOutputStream fos = new FileOutputStream("d:/tt.xls"); - workbook.write(fos); - fos.close(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } + @Test + public void test() { + try { + List entity = new ArrayList(); + entity.add(new ExcelExportEntity("姓名", "name")); + entity.add(new ExcelExportEntity("性别", "sex")); + + List> list = new ArrayList>(); + Map map; + for (int i = 0; i < 10; i++) { + map = new HashMap(); + map.put("name", "1" + i); + map.put("sex", "2" + i); + list.add(map); + } + + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(new ExportParams("测试", "测试"), + entity, list); + FileOutputStream fos = new FileOutputStream("d:/tt.xls"); + workbook.write(fos); + fos.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportTemplateTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportTemplateTest.java index deb0199..4c7f731 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportTemplateTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/excel/test/ExcelExportTemplateTest.java @@ -1,7 +1,6 @@ package org.jeecgframework.poi.excel.test; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Date; @@ -19,90 +18,88 @@ import org.junit.Before; import org.junit.Test; public class ExcelExportTemplateTest { - - List list = new ArrayList(); - CourseEntity courseEntity; - @Before - public void testBefore() { - courseEntity = new CourseEntity(); - courseEntity.setId("1131"); - courseEntity.setName("小白"); + List list = new ArrayList(); + CourseEntity courseEntity; - 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); - } - } - - //@Test - public void one () throws Exception{ - TemplateExportParams params = new TemplateExportParams(); - params.setHeadingRows(2); - params.setHeadingStartRow(2); - Map map = new HashMap(); + //@Test + public void one() throws Exception { + TemplateExportParams params = new TemplateExportParams(); + params.setHeadingRows(2); + params.setHeadingStartRow(2); + Map map = new HashMap(); map.put("year", "2013"); map.put("sunCourses", list.size()); - Map obj = new HashMap(); + Map obj = new HashMap(); map.put("obj", obj); obj.put("name", list.size()); - params.setTemplateUrl("org/jeecgframework/poi/excel/doc/exportTemp.xls"); - Workbook book = ExcelExportUtil.exportExcel(params, CourseEntity.class, list, - map); - File savefile = new File("d:/"); - if (!savefile.exists()) { - savefile.mkdirs(); - } - FileOutputStream fos = new FileOutputStream("d:/exportTemp.xls"); - book.write(fos); - fos.close(); - - } - @Test - public void two () throws Exception{ - TemplateExportParams params = new TemplateExportParams(); - Map map = new HashMap(); - map.put("month", 10); - Map temp; - for(int i = 1;i<8;i++){ - temp = new HashMap(); - temp.put("per", i*10); - temp.put("mon", i*1000); - temp.put("summon", i*10000); - map.put("i"+i, temp); - } - params.setTemplateUrl("org/jeecgframework/poi/excel/doc/exportTemp.xls"); - params.setSheetNum(1); - Workbook book = ExcelExportUtil.exportExcel(params, CourseEntity.class, list, - map); - File savefile = new File("d:/"); - if (!savefile.exists()) { - savefile.mkdirs(); - } - FileOutputStream fos = new FileOutputStream("d:/exportTemp2.xls"); - book.write(fos); - fos.close(); - - } - + params.setTemplateUrl("org/jeecgframework/poi/excel/doc/exportTemp.xls"); + Workbook book = ExcelExportUtil.exportExcel(params, CourseEntity.class, list, map); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/exportTemp.xls"); + book.write(fos); + fos.close(); + + } + + @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); + } + } + + @Test + public void two() throws Exception { + TemplateExportParams params = new TemplateExportParams(); + Map map = new HashMap(); + map.put("month", 10); + Map temp; + for (int i = 1; i < 8; i++) { + temp = new HashMap(); + temp.put("per", i * 10); + temp.put("mon", i * 1000); + temp.put("summon", i * 10000); + map.put("i" + i, temp); + } + params.setTemplateUrl("org/jeecgframework/poi/excel/doc/exportTemp.xls"); + params.setSheetNum(1); + Workbook book = ExcelExportUtil.exportExcel(params, CourseEntity.class, list, map); + File savefile = new File("d:/"); + if (!savefile.exists()) { + savefile.mkdirs(); + } + FileOutputStream fos = new FileOutputStream("d:/exportTemp2.xls"); + book.write(fos); + fos.close(); + + } } 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 index de1da89..0450657 100644 --- 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 @@ -1,5 +1,10 @@ package org.jeecgframework.poi.excel.test; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jeecgframework.poi.entity.CourseEntity; import org.jeecgframework.poi.entity.StudentEntity; @@ -9,65 +14,59 @@ 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; + List list = new ArrayList(); + CourseEntity courseEntity; - @Before - public void testBefore() { - courseEntity = new CourseEntity(); - courseEntity.setId("1131"); - courseEntity.setName("小白"); + @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 teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); - teacherEntity = new TeacherEntity(); - teacherEntity.setId("121312314312421131"); - teacherEntity.setName("老王"); - courseEntity.setShuxueteacher(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); + 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); - } - } + 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(); - } + /** + * 基本导出测试 + * + * @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 index f1c91c4..fab3b60 100644 --- 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 @@ -1,5 +1,10 @@ package org.jeecgframework.poi.excel.test; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jeecgframework.poi.entity.CourseEntity; import org.jeecgframework.poi.entity.StudentEntity; @@ -9,71 +14,65 @@ 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; + List list = new ArrayList(); + List telist = new ArrayList(); + CourseEntity courseEntity; - @Before - public void testBefore() { - courseEntity = new CourseEntity(); - courseEntity.setId("1131"); - courseEntity.setName("小白"); + @Before + public void testBefor2() { + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12132131231231231"); + teacherEntity.setName("你们"); - TeacherEntity teacherEntity = new TeacherEntity(); - teacherEntity.setId("12131231"); - teacherEntity.setName("你们"); - courseEntity.setTeacher(teacherEntity); + for (int i = 0; i < 3; i++) { + telist.add(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); + @Before + public void testBefore() { + courseEntity = new CourseEntity(); + courseEntity.setId("1131"); + courseEntity.setName("小白"); - for (int i = 0; i < 3; i++) { - list.add(courseEntity); - } - } + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); - @Before - public void testBefor2() { - TeacherEntity teacherEntity = new TeacherEntity(); - teacherEntity.setId("12132131231231231"); - teacherEntity.setName("你们"); + 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++) { - telist.add(teacherEntity); - } - } + for (int i = 0; i < 3; i++) { + list.add(courseEntity); + } + } - /** - * 单行表头导出测试 - * - * @throws Exception - */ - @Test - public void testExportExcel() throws Exception { - ExportParams params = new ExportParams("2412312", "测试", "测试"); - params.setAddIndex(true); - HSSFWorkbook workbook = ExcelExportUtil.exportExcel(params, - TeacherEntity.class, telist); - FileOutputStream fos = new FileOutputStream("d:/tt.xls"); - workbook.write(fos); - fos.close(); - } + /** + * 单行表头导出测试 + * + * @throws Exception + */ + @Test + public void testExportExcel() throws Exception { + ExportParams params = new ExportParams("2412312", "测试", "测试"); + params.setAddIndex(true); + HSSFWorkbook workbook = ExcelExportUtil.exportExcel(params, 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 index 094b9a8..5eea56f 100644 --- 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 @@ -1,5 +1,12 @@ package org.jeecgframework.poi.excel.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; + import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.jeecgframework.poi.entity.CourseEntity; @@ -11,143 +18,137 @@ 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; + List list = new ArrayList(); + CourseEntity courseEntity; + + /** + * 25W行导出测试 + * + * @throws Exception + */ + @Test + public void oneHundredThousandRowTest() throws Exception { + + for (int i = 0; i < 250; 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(); + savefile = new File("d:/1"); + if (!savefile.exists()) { + savefile.setWritable(true, false); + savefile.mkdirs(); + } + fos = new FileOutputStream("d:/1/tt3.xls"); + workbook.write(fos); + fos.close(); + } + + @Before + public void testBefore() { + courseEntity = new CourseEntity(); + courseEntity.setId("1131"); + courseEntity.setName("小白"); + + TeacherEntity teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); - @Before - public void testBefore() { - courseEntity = new CourseEntity(); - courseEntity.setId("1131"); - courseEntity.setName("小白"); + teacherEntity = new TeacherEntity(); + teacherEntity.setId("121312314312421131"); + teacherEntity.setName("老王"); + courseEntity.setShuxueteacher(teacherEntity); - 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); - 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); + } + } - 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 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 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 < 250; 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(); - savefile = new File("d:/1"); - if (!savefile.exists()) { - savefile.setWritable(true, false); - savefile.mkdirs(); - } - fos = new FileOutputStream("d:/1/tt3.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(); + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilAnnExcelTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilAnnExcelTest.java index 17bc646..acdfaa5 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilAnnExcelTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilAnnExcelTest.java @@ -1,7 +1,5 @@ package org.jeecgframework.poi.word; -import static org.junit.Assert.*; - import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -15,7 +13,6 @@ import org.jeecgframework.poi.entity.CourseEntity; import org.jeecgframework.poi.entity.StudentEntity; import org.jeecgframework.poi.entity.TeacherEntity; import org.jeecgframework.poi.word.entity.Person; -import org.jeecgframework.poi.word.entity.WordImageEntity; import org.jeecgframework.poi.word.entity.params.ExcelListEntity; import org.junit.Before; import org.junit.Test; @@ -28,92 +25,92 @@ import org.junit.Test; */ public class WordExportUtilAnnExcelTest { - private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); - - List list = new ArrayList(); - CourseEntity courseEntity; + private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); + + List list = new ArrayList(); + CourseEntity courseEntity; + + /** + * 简单导出没有图片和Excel + */ + //@Test + public void SimpleWordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("auditPerson", "JueYue"); + map.put("time", format.format(new Date())); + List list = new ArrayList(); + Person p = new Person(); + p.setName("小明"); + p.setTel("18711111111"); + p.setEmail("18711111111@139.com"); + list.add(p); + p = new Person(); + p.setName("小红"); + p.setTel("18711111112"); + p.setEmail("18711111112@139.com"); + list.add(p); + map.put("pList", new ExcelListEntity(list, Person.class)); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/SimpleExcel.docx", map); + FileOutputStream fos = new FileOutputStream("d:/simpleExcel.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } - @Before - public void testBefore() { - courseEntity = new CourseEntity(); - courseEntity.setId("1131"); - courseEntity.setName("小白"); + @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 teacherEntity = new TeacherEntity(); + teacherEntity.setId("12131231"); + teacherEntity.setName("你们"); + courseEntity.setTeacher(teacherEntity); - teacherEntity = new TeacherEntity(); - teacherEntity.setId("121312314312421131"); - teacherEntity.setName("老王"); - courseEntity.setShuxueteacher(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); + 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); - } - } + for (int i = 0; i < 3; i++) { + list.add(courseEntity); + } + } - /** - * 简单导出没有图片和Excel - */ - //@Test - public void SimpleWordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("auditPerson", "JueYue"); - map.put("time", format.format(new Date())); - List list = new ArrayList(); - Person p = new Person(); - p.setName("小明"); - p.setTel("18711111111"); - p.setEmail("18711111111@139.com"); - list.add(p); - p = new Person(); - p.setName("小红"); - p.setTel("18711111112"); - p.setEmail("18711111112@139.com"); - list.add(p); - map.put("pList", new ExcelListEntity(list, Person.class)); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/SimpleExcel.docx", map); - FileOutputStream fos = new FileOutputStream("d:/simpleExcel.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void WordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("auditPerson", "JueYue"); - map.put("time", format.format(new Date())); - map.put("cs", new ExcelListEntity(list, CourseEntity.class)); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/Excel.docx", map); - FileOutputStream fos = new FileOutputStream("d:/Excel.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + @Test + public void WordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("auditPerson", "JueYue"); + map.put("time", format.format(new Date())); + map.put("cs", new ExcelListEntity(list, CourseEntity.class)); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/Excel.docx", map); + FileOutputStream fos = new FileOutputStream("d:/Excel.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilBaseExcelTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilBaseExcelTest.java index 1d070fb..728ad42 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilBaseExcelTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilBaseExcelTest.java @@ -1,7 +1,5 @@ package org.jeecgframework.poi.word; -import static org.junit.Assert.*; - import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -17,63 +15,65 @@ import org.junit.Test; public class WordExportUtilBaseExcelTest { - private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); - /** - * 简单导出没有图片和Excel - */ - @Test - public void SimpleWordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("auditPerson", "JueYue"); - map.put("time", format.format(new Date())); - List list = new ArrayList(); - Person p = new Person(); - p.setName("小明"); - p.setTel("18711111111"); - p.setEmail("18711111111@139.com"); - list.add(p); - p = new Person(); - p.setName("小红"); - p.setTel("18711111112"); - p.setEmail("18711111112@139.com"); - list.add(p); - map.put("pList", list); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/SimpleExcel.docx", map); - FileOutputStream fos = new FileOutputStream("d:/simpleExcel.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - /** - * 简单导出包含图片 - */ - //@Test - public void imageWordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("time", format.format(new Date())); - WordImageEntity image = new WordImageEntity(); - image.setHeight(200); - image.setWidth(500); - image.setUrl("org/jeecgframework/poi/word/img/testCode.png"); - image.setType(WordImageEntity.URL); - map.put("testCode", image); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/Image.docx", map); - FileOutputStream fos = new FileOutputStream("d:/image.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); + + /** + * 简单导出包含图片 + */ + //@Test + public void imageWordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("time", format.format(new Date())); + WordImageEntity image = new WordImageEntity(); + image.setHeight(200); + image.setWidth(500); + image.setUrl("org/jeecgframework/poi/word/img/testCode.png"); + image.setType(WordImageEntity.URL); + map.put("testCode", image); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/Image.docx", map); + FileOutputStream fos = new FileOutputStream("d:/image.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 简单导出没有图片和Excel + */ + @Test + public void SimpleWordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("auditPerson", "JueYue"); + map.put("time", format.format(new Date())); + List list = new ArrayList(); + Person p = new Person(); + p.setName("小明"); + p.setTel("18711111111"); + p.setEmail("18711111111@139.com"); + list.add(p); + p = new Person(); + p.setName("小红"); + p.setTel("18711111112"); + p.setEmail("18711111112@139.com"); + list.add(p); + map.put("pList", list); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/SimpleExcel.docx", map); + FileOutputStream fos = new FileOutputStream("d:/simpleExcel.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilTest.java b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilTest.java index f817f21..4f38287 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilTest.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/word/WordExportUtilTest.java @@ -12,50 +12,52 @@ import org.junit.Test; public class WordExportUtilTest { - private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); - /** - * 简单导出没有图片和Excel - */ - @Test - public void SimpleWordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("time", format.format(new Date())); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/Simple.docx", map); - FileOutputStream fos = new FileOutputStream("d:/simple.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - /** - * 简单导出包含图片 - */ - @Test - public void imageWordExport() { - Map map = new HashMap(); - map.put("department", "Jeecg"); - map.put("person", "JueYue"); - map.put("time", format.format(new Date())); - WordImageEntity image = new WordImageEntity(); - image.setHeight(200); - image.setWidth(500); - image.setUrl("org/jeecgframework/poi/word/img/testCode.png"); - image.setType(WordImageEntity.URL); - map.put("testCode", image); - try { - XWPFDocument doc = WordExportUtil.exportWord07( - "org/jeecgframework/poi/word/doc/Image.docx", map); - FileOutputStream fos = new FileOutputStream("d:/image.docx"); - doc.write(fos); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + private static SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd"); + + /** + * 简单导出包含图片 + */ + @Test + public void imageWordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("time", format.format(new Date())); + WordImageEntity image = new WordImageEntity(); + image.setHeight(200); + image.setWidth(500); + image.setUrl("org/jeecgframework/poi/word/img/testCode.png"); + image.setType(WordImageEntity.URL); + map.put("testCode", image); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/Image.docx", map); + FileOutputStream fos = new FileOutputStream("d:/image.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 简单导出没有图片和Excel + */ + @Test + public void SimpleWordExport() { + Map map = new HashMap(); + map.put("department", "Jeecg"); + map.put("person", "JueYue"); + map.put("time", format.format(new Date())); + try { + XWPFDocument doc = WordExportUtil.exportWord07( + "org/jeecgframework/poi/word/doc/Simple.docx", map); + FileOutputStream fos = new FileOutputStream("d:/simple.docx"); + doc.write(fos); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/easypoi-test/src/main/java/org/jeecgframework/poi/word/entity/Person.java b/easypoi-test/src/main/java/org/jeecgframework/poi/word/entity/Person.java index bec1850..01f31a1 100644 --- a/easypoi-test/src/main/java/org/jeecgframework/poi/word/entity/Person.java +++ b/easypoi-test/src/main/java/org/jeecgframework/poi/word/entity/Person.java @@ -8,36 +8,36 @@ import org.jeecgframework.poi.excel.annotation.Excel; * @date 2014年7月26日 下午10:51:30 */ public class Person { - - @Excel(name = "姓名") - private String name; - @Excel(name = "手机") - private String tel; - @Excel(name = "Email") - private String email; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTel() { - return tel; - } - - public void setTel(String tel) { - this.tel = tel; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } + + @Excel(name = "姓名") + private String name; + @Excel(name = "手机") + private String tel; + @Excel(name = "Email") + private String email; + + public String getEmail() { + return email; + } + + public String getName() { + return name; + } + + public String getTel() { + return tel; + } + + public void setEmail(String email) { + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setTel(String tel) { + this.tel = tel; + } } 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 index b351701..6c41899 100644 --- 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 @@ -1,19 +1,20 @@ 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 CLASS = "entity"; /** *表格参数 */ - public final static String PARAMS = "params"; + public final static String PARAMS = "params"; /** *下载文件名称 */ diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/MapExcelConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/MapExcelConstants.java index 6d67a29..cf8d41b 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/MapExcelConstants.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/MapExcelConstants.java @@ -13,10 +13,10 @@ public interface MapExcelConstants extends BasePOIConstants { /** * Entity List */ - public final static String ENTITY_LIST = "data"; + public final static String ENTITY_LIST = "data"; /** * 数据列表 */ - public final static String MAP_LIST = "mapList"; + public final static String MAP_LIST = "mapList"; } diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalExcelConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalExcelConstants.java index 6ac0058..7e6d6a1 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalExcelConstants.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/NormalExcelConstants.java @@ -13,10 +13,10 @@ public interface NormalExcelConstants extends BasePOIConstants { /** * 数据列表 */ - public final static String DATA_LIST = "data"; + public final static String DATA_LIST = "data"; /** * 多Sheet 对象 */ - public final static String MAP_LIST = "mapList"; + public final static String MAP_LIST = "mapList"; } diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateExcelConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateExcelConstants.java index 82d9609..1a0d496 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateExcelConstants.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateExcelConstants.java @@ -1,21 +1,22 @@ package org.jeecgframework.poi.excel.entity.vo; + /** * 模板Excel导出常量 * @author JueYue * @date 2014年6月30日 下午9:26:52 */ public interface TemplateExcelConstants extends BasePOIConstants { - /** + /** * 模板导出 */ public final static String JEECG_TEMPLATE_EXCEL_VIEW = "jeecgTemplateExcelView"; /** * 数据列表 */ - public final static String LIST_DATA = "list"; + public final static String LIST_DATA = "list"; /** * 模板参数 */ - public final static String MAP_DATA = "map"; + public final static String MAP_DATA = "map"; } diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateWordConstants.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateWordConstants.java index c21bf67..6fa8b9e 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateWordConstants.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/entity/vo/TemplateWordConstants.java @@ -1,21 +1,22 @@ package org.jeecgframework.poi.excel.entity.vo; + /** * Word 导出模板常量 * @author JueYue * @date 2014年7月24日 下午11:26:46 */ public interface TemplateWordConstants extends BasePOIConstants { - /** + /** * 模板导出 */ public final static String JEECG_TEMPLATE_WORD_VIEW = "jeecgTemplateWordView"; /** * 数据列表 */ - public final static String URL = "url"; + public final static String URL = "url"; /** * 模板参数 */ - public final static String MAP_DATA = "map"; + public final static String MAP_DATA = "map"; } diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgMapExcelView.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgMapExcelView.java index 04114cb..5013b8f 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgMapExcelView.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgMapExcelView.java @@ -1,5 +1,12 @@ package org.jeecgframework.poi.excel.view; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; @@ -7,13 +14,6 @@ import org.jeecgframework.poi.excel.entity.vo.MapExcelConstants; 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; - /** * Map 对象接口 * @@ -23,34 +23,29 @@ import java.util.Map; @SuppressWarnings("unchecked") public class JeecgMapExcelView extends AbstractExcelView { - @Override - protected void buildExcelDocument(Map model, - HSSFWorkbook hssfWorkbook, HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse) throws Exception { - String codedFileName = "临时文件.xls"; - if (model.containsKey(MapExcelConstants.FILE_NAME)) { - codedFileName = (String) model.get(MapExcelConstants.FILE_NAME) - + ".xls"; - } - if (isIE(httpServletRequest)) { - codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); - } else { - codedFileName = new String(codedFileName.getBytes("UTF-8"), - "ISO-8859-1"); - } - httpServletResponse.setHeader("content-disposition", - "attachment;filename=" + codedFileName); - new ExcelExportServer().createSheetForMap(hssfWorkbook, - (ExportParams) model.get(MapExcelConstants.PARAMS), - (List) model - .get(MapExcelConstants.ENTITY_LIST), - (Collection>) model - .get(MapExcelConstants.MAP_LIST)); - } + @Override + protected void buildExcelDocument(Map model, HSSFWorkbook hssfWorkbook, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse) throws Exception { + String codedFileName = "临时文件.xls"; + if (model.containsKey(MapExcelConstants.FILE_NAME)) { + codedFileName = (String) model.get(MapExcelConstants.FILE_NAME) + ".xls"; + } + if (isIE(httpServletRequest)) { + codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); + } else { + codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1"); + } + httpServletResponse + .setHeader("content-disposition", "attachment;filename=" + codedFileName); + new ExcelExportServer().createSheetForMap(hssfWorkbook, + (ExportParams) model.get(MapExcelConstants.PARAMS), + (List) model.get(MapExcelConstants.ENTITY_LIST), + (Collection>) model.get(MapExcelConstants.MAP_LIST)); + } - public boolean isIE(HttpServletRequest request) { - return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request - .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true - : false; - } + public boolean isIE(HttpServletRequest request) { + return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request + .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true : false; + } } 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 index 0d2eef7..bb241be 100644 --- 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 @@ -1,63 +1,58 @@ package org.jeecgframework.poi.excel.view; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants; 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(NormalExcelConstants.FILE_NAME)) { - codedFileName = (String) model.get(NormalExcelConstants.FILE_NAME) - + ".xls"; - } - if (isIE(httpServletRequest)) { - codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); - } else { - codedFileName = new String(codedFileName.getBytes("UTF-8"), - "ISO-8859-1"); - } - httpServletResponse.setHeader("content-disposition", - "attachment;filename="+codedFileName); - if (model.containsKey(NormalExcelConstants.MAP_LIST)) { - List> list = (List>) model - .get(NormalExcelConstants.MAP_LIST); - for (Map map : list) { - new ExcelExportServer() - .createSheet(hssfWorkbook, (ExportParams) map - .get(NormalExcelConstants.PARAMS), - (Class) map.get(NormalExcelConstants.CLASS), - (Collection) map - .get(NormalExcelConstants.DATA_LIST)); - } - } else { - new ExcelExportServer().createSheet(hssfWorkbook, - (ExportParams) model.get(NormalExcelConstants.PARAMS), - (Class) model.get(NormalExcelConstants.CLASS), - (Collection) model.get(NormalExcelConstants.DATA_LIST)); - } - } + @Override + protected void buildExcelDocument(Map model, HSSFWorkbook hssfWorkbook, + HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse) throws Exception { + String codedFileName = "临时文件.xls"; + if (model.containsKey(NormalExcelConstants.FILE_NAME)) { + codedFileName = (String) model.get(NormalExcelConstants.FILE_NAME) + ".xls"; + } + if (isIE(httpServletRequest)) { + codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); + } else { + codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1"); + } + httpServletResponse + .setHeader("content-disposition", "attachment;filename=" + codedFileName); + if (model.containsKey(NormalExcelConstants.MAP_LIST)) { + List> list = (List>) model + .get(NormalExcelConstants.MAP_LIST); + for (Map map : list) { + new ExcelExportServer().createSheet(hssfWorkbook, + (ExportParams) map.get(NormalExcelConstants.PARAMS), + (Class) map.get(NormalExcelConstants.CLASS), + (Collection) map.get(NormalExcelConstants.DATA_LIST)); + } + } else { + new ExcelExportServer().createSheet(hssfWorkbook, + (ExportParams) model.get(NormalExcelConstants.PARAMS), + (Class) model.get(NormalExcelConstants.CLASS), + (Collection) model.get(NormalExcelConstants.DATA_LIST)); + } + } - public boolean isIE(HttpServletRequest request) { - return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request - .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true - : false; - } + public boolean isIE(HttpServletRequest request) { + return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request + .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true : false; + } } 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 index 12957b1..2d19a8f 100644 --- 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 @@ -23,42 +23,37 @@ import org.springframework.web.servlet.view.AbstractView; @SuppressWarnings("unchecked") public class JeecgTemplateExcelView extends AbstractView { - private static final String CONTENT_TYPE = "application/vnd.ms-excel"; + private static final String CONTENT_TYPE = "application/vnd.ms-excel"; - public JeecgTemplateExcelView() { - setContentType(CONTENT_TYPE); - } + public JeecgTemplateExcelView() { + setContentType(CONTENT_TYPE); + } - @Override - protected void renderMergedOutputModel(Map model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { - String codedFileName = "临时文件.xls"; - if (model.containsKey(NormalExcelConstants.FILE_NAME)) { - codedFileName = (String) model.get(NormalExcelConstants.FILE_NAME) - + ".xls"; - } - if (isIE(request)) { - codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); - } else { - codedFileName = new String(codedFileName.getBytes("UTF-8"), - "ISO-8859-1"); - } - response.setHeader("content-disposition", - "attachment;filename="+codedFileName); - Workbook workbook = ExcelExportUtil.exportExcel( - (TemplateExportParams)model.get(TemplateExcelConstants.PARAMS), - (Class) model.get(TemplateExcelConstants.CLASS), - (List)model.get(TemplateExcelConstants.LIST_DATA), - (Map)model.get(TemplateExcelConstants.MAP_DATA)); - ServletOutputStream out = response.getOutputStream(); - workbook.write(out); - out.flush(); - } - - public boolean isIE(HttpServletRequest request) { - return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request - .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true - : false; - } + public boolean isIE(HttpServletRequest request) { + return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request + .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true : false; + } + + @Override + protected void renderMergedOutputModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { + String codedFileName = "临时文件.xls"; + if (model.containsKey(NormalExcelConstants.FILE_NAME)) { + codedFileName = (String) model.get(NormalExcelConstants.FILE_NAME) + ".xls"; + } + if (isIE(request)) { + codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); + } else { + codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1"); + } + response.setHeader("content-disposition", "attachment;filename=" + codedFileName); + Workbook workbook = ExcelExportUtil.exportExcel( + (TemplateExportParams) model.get(TemplateExcelConstants.PARAMS), + (Class) model.get(TemplateExcelConstants.CLASS), + (List) model.get(TemplateExcelConstants.LIST_DATA), + (Map) model.get(TemplateExcelConstants.MAP_DATA)); + ServletOutputStream out = response.getOutputStream(); + workbook.write(out); + out.flush(); + } } diff --git a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateWordView.java b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateWordView.java index 3e449eb..6aae99f 100644 --- a/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateWordView.java +++ b/easypoi-web/src/main/java/org/jeecgframework/poi/excel/view/JeecgTemplateWordView.java @@ -20,41 +20,35 @@ import org.springframework.web.servlet.view.AbstractView; @SuppressWarnings("unchecked") public class JeecgTemplateWordView extends AbstractView { - private static final String CONTENT_TYPE = "application/msword"; - - public JeecgTemplateWordView() { - setContentType(CONTENT_TYPE); - } - - @Override - protected void renderMergedOutputModel(Map model, - HttpServletRequest request, HttpServletResponse response) - throws Exception { - String codedFileName = "临时文件.docx"; - if (model.containsKey(TemplateWordConstants.FILE_NAME)) { - codedFileName = (String) model.get(TemplateWordConstants.FILE_NAME) - + ".docx"; - } - if (isIE(request)) { - codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); - } else { - codedFileName = new String(codedFileName.getBytes("UTF-8"), - "ISO-8859-1"); - } - response.setHeader("content-disposition", "attachment;filename=" - + codedFileName); - XWPFDocument document = WordExportUtil - .exportWord07((String) model.get(TemplateWordConstants.URL), - (Map) model - .get(TemplateWordConstants.MAP_DATA)); - ServletOutputStream out = response.getOutputStream(); - document.write(out); - out.flush(); - } - - public boolean isIE(HttpServletRequest request) { - return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request - .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true - : false; - } + private static final String CONTENT_TYPE = "application/msword"; + + public JeecgTemplateWordView() { + setContentType(CONTENT_TYPE); + } + + public boolean isIE(HttpServletRequest request) { + return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request + .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true : false; + } + + @Override + protected void renderMergedOutputModel(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { + String codedFileName = "临时文件.docx"; + if (model.containsKey(TemplateWordConstants.FILE_NAME)) { + codedFileName = (String) model.get(TemplateWordConstants.FILE_NAME) + ".docx"; + } + if (isIE(request)) { + codedFileName = java.net.URLEncoder.encode(codedFileName, "UTF8"); + } else { + codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1"); + } + response.setHeader("content-disposition", "attachment;filename=" + codedFileName); + XWPFDocument document = WordExportUtil.exportWord07( + (String) model.get(TemplateWordConstants.URL), + (Map) model.get(TemplateWordConstants.MAP_DATA)); + ServletOutputStream out = response.getOutputStream(); + document.write(out); + out.flush(); + } }