From fce6aae8c6017d9d1edef3d67cfe4da718bd9e15 Mon Sep 17 00:00:00 2001 From: jueyue Date: Thu, 24 Jul 2014 23:07:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Word=20=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E5=B7=A5=E5=85=B7=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jeecgframework/poi/cache/WordCache.java | 35 +++ .../poi/cache/manager/FileLoade.java | 4 +- .../poi/excel/export/ExcelExportBase.java | 22 +- .../poi/excel/export/ExcelExportServer.java | 4 +- .../template/ExcelExportOfTemplateUtil.java | 6 +- .../poi/excel/imports/ExcelImportServer.java | 42 +-- ...xcelPublicUtil.java => POIPublicUtil.java} | 4 +- .../poi/word/WordExportUtil.java | 28 ++ .../poi/word/entity/JeecgXWPFDocument.java | 157 ++++++++++ .../poi/word/entity/WordImageEntity.java | 67 +++++ .../poi/word/parse/ParseWord07.java | 282 ++++++++++++++++++ .../poi/word/util/ParseWordUtil.java | 143 +++++++++ .../easypoi-base/pom.properties | 2 +- 13 files changed, 754 insertions(+), 42 deletions(-) create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/cache/WordCache.java rename easypoi-base/src/main/java/org/jeecgframework/poi/util/{ExcelPublicUtil.java => POIPublicUtil.java} (95%) create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java create mode 100644 easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java 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 new file mode 100644 index 0000000..f5ce5a6 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/cache/WordCache.java @@ -0,0 +1,35 @@ +package org.jeecgframework.poi.cache; + +import java.io.IOException; +import java.io.InputStream; + +import org.jeecgframework.poi.cache.manager.POICacheManager; +import org.jeecgframework.poi.word.entity.JeecgXWPFDocument; + +/** + * word 缓存中心 + * + * @author JueYue + * @date 2014年7月24日 下午10:54:31 + */ +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; + } + +} 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 8d6c660..efd378a 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 @@ -5,7 +5,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; -import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.jeecgframework.poi.util.POIPublicUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,7 +23,7 @@ class FileLoade { FileInputStream fileis = null; ByteArrayOutputStream baos = null; try { - String path = ExcelPublicUtil.getWebRootPath(url); + String path = POIPublicUtil.getWebRootPath(url); fileis = new FileInputStream(path); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java index 628a929..88d400e 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/excel/export/ExcelExportBase.java @@ -40,7 +40,7 @@ import org.jeecgframework.poi.excel.entity.params.ComparatorExcelField; import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; import org.jeecgframework.poi.excel.entity.params.MergeEntity; import org.jeecgframework.poi.handler.inter.IExcelDataHandler; -import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.jeecgframework.poi.util.POIPublicUtil; /** * 导出基础服务 @@ -73,11 +73,11 @@ public abstract class ExcelExportBase { for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // 先判断是不是collection,在判断是不是java自带对象,之后就是我们自己的对象了 - if (ExcelPublicUtil.isNotUserExcelUserThis(exclusionsList, field, + if (POIPublicUtil.isNotUserExcelUserThis(exclusionsList, field, targetId)) { continue; } - if (ExcelPublicUtil.isCollection(field.getType())) { + if (POIPublicUtil.isCollection(field.getType())) { ExcelCollection excel = field .getAnnotation(ExcelCollection.class); ParameterizedType pt = (ParameterizedType) field @@ -87,16 +87,16 @@ public abstract class ExcelExportBase { getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, - ExcelPublicUtil.getClassFields(clz), list, clz, null); + POIPublicUtil.getClassFields(clz), list, clz, null); excelEntity = new ExcelExportEntity(); excelEntity.setName(getExcelName(excel.name(), targetId)); excelEntity .setOrderNum(getCellOrder(excel.orderNum(), targetId)); - excelEntity.setMethod(ExcelPublicUtil.getMethod( + excelEntity.setMethod(POIPublicUtil.getMethod( field.getName(), pojoClass)); excelEntity.setList(list); excelParams.add(excelEntity); - } else if (ExcelPublicUtil.isJavaClass(field)) { + } else if (POIPublicUtil.isJavaClass(field)) { excelParams.add(createExcelExportEntity(field, targetId, pojoClass, getMethods)); } else { @@ -104,13 +104,13 @@ public abstract class ExcelExportBase { if (getMethods != null) { newMethods.addAll(getMethods); } - newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + newMethods.add(POIPublicUtil.getMethod(field.getName(), pojoClass)); ExcelEntity excel = field.getAnnotation(ExcelEntity.class); getAllExcelField(exclusions, StringUtils.isNotEmpty(excel.id()) ? excel.id() : targetId, - ExcelPublicUtil.getClassFields(field.getType()), + POIPublicUtil.getClassFields(field.getType()), excelParams, field.getType(), newMethods); } } @@ -224,7 +224,7 @@ public abstract class ExcelExportBase { .setFormat(StringUtils.isNotEmpty(excel.exportFormat()) ? excel .exportFormat() : excel.format()); String fieldname = field.getName(); - excelEntity.setMethod(ExcelPublicUtil.getMethod(fieldname, pojoClass)); + excelEntity.setMethod(POIPublicUtil.getMethod(fieldname, pojoClass)); } /** @@ -650,7 +650,7 @@ public abstract class ExcelExportBase { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); BufferedImage bufferImg; try { - String path = ExcelPublicUtil.getWebRootPath(string); + String path = POIPublicUtil.getWebRootPath(string); path = path.replace("WEB-INF/classes/", ""); path = path.replace("file:/", ""); bufferImg = ImageIO.read(new File(path)); @@ -685,7 +685,7 @@ public abstract class ExcelExportBase { * @date 2013年11月25日 */ public int getImageType(byte[] value) { - String type = ExcelPublicUtil.getFileExtendName(value); + String type = POIPublicUtil.getFileExtendName(value); if (type.equalsIgnoreCase("JPG")) { return HSSFWorkbook.PICTURE_TYPE_JPEG; } else if (type.equalsIgnoreCase("PNG")) { 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 440d240..d3bff42 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 @@ -24,7 +24,7 @@ import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; import org.jeecgframework.poi.exception.excel.ExcelExportException; import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; -import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.jeecgframework.poi.util.POIPublicUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -71,7 +71,7 @@ public class ExcelExportServer extends ExcelExportBase { Drawing patriarch = sheet.createDrawingPatriarch(); List excelParams = new ArrayList(); // 得到所有字段 - Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + Field fileds[] = POIPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); String targetId = etarget == null ? null : etarget.value(); getAllExcelField(entity.getExclusions(), targetId, fileds, 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 b9e783a..afa2a1e 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 @@ -22,7 +22,7 @@ import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity; import org.jeecgframework.poi.excel.export.ExcelExportBase; import org.jeecgframework.poi.exception.excel.ExcelExportException; import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum; -import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.jeecgframework.poi.util.POIPublicUtil; /** * Excel 导出根据模板导出 @@ -101,7 +101,7 @@ public final class ExcelExportOfTemplateUtil extends ExcelExportBase { Map titlemap = getTitleMap(params, sheet); Drawing patriarch = sheet.createDrawingPatriarch(); // 得到所有字段 - Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + Field fileds[] = POIPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); String targetId = null; if (etarget != null) { @@ -258,7 +258,7 @@ public final class ExcelExportOfTemplateUtil extends ExcelExportBase { if (object instanceof Map) { object = ((Map) object).get(paramsArr[index]); } else { - object = ExcelPublicUtil.getMethod(paramsArr[index], + object = POIPublicUtil.getMethod(paramsArr[index], object.getClass()).invoke(object, new Object[] {}); } return (index == paramsArr.length - 1) ? (object == null ? "" : object 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 e26621f..0d745a1 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 @@ -40,7 +40,7 @@ import org.jeecgframework.poi.excel.entity.params.ExcelVerifyEntity; import org.jeecgframework.poi.excel.entity.result.ExcelImportResult; import org.jeecgframework.poi.excel.entity.result.ExcelVerifyHanlderResult; import org.jeecgframework.poi.excel.imports.verifys.VerifyHandlerServer; -import org.jeecgframework.poi.util.ExcelPublicUtil; +import org.jeecgframework.poi.util.POIPublicUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -95,10 +95,10 @@ public class ExcelImportServer { Map pictures; for (int i = 0; i < params.getSheetNum(); i++) { if (isXSSFWorkbook) { - pictures = ExcelPublicUtil.getSheetPictrues07( + pictures = POIPublicUtil.getSheetPictrues07( (XSSFSheet) book.getSheetAt(i), (XSSFWorkbook) book); } else { - pictures = ExcelPublicUtil.getSheetPictrues03( + pictures = POIPublicUtil.getSheetPictrues03( (HSSFSheet) book.getSheetAt(i), (HSSFWorkbook) book); } result.addAll(importExcel(result, book.getSheetAt(i), pojoClass, @@ -112,7 +112,7 @@ public class ExcelImportServer { private void saveThisExcel(ImportParams params, Class pojoClass, boolean isXSSFWorkbook, Workbook book) throws Exception { - String path = ExcelPublicUtil.getWebRootPath(getSaveExcelUrl(params, + String path = POIPublicUtil.getWebRootPath(getSaveExcelUrl(params, pojoClass)); File savefile = new File(path); if (!savefile.exists()) { @@ -153,7 +153,7 @@ public class ExcelImportServer { List collection = new ArrayList(); Map excelParams = new HashMap(); List excelCollection = new ArrayList(); - Field fileds[] = ExcelPublicUtil.getClassFields(pojoClass); + Field fileds[] = POIPublicUtil.getClassFields(pojoClass); ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class); String targetId = null; if (etarget != null) { @@ -194,7 +194,7 @@ public class ExcelImportServer { pictures, params); } } else { - object = ExcelPublicUtil.createObject(pojoClass, targetId); + 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); @@ -293,9 +293,9 @@ public class ExcelImportServer { PictureData image = pictures.get(picId); byte[] data = image.getData(); String fileName = "pic" + Math.round(Math.random() * 100000000000L); - fileName += "." + ExcelPublicUtil.getFileExtendName(data); + fileName += "." + POIPublicUtil.getFileExtendName(data); if (excelParams.get(titleString).getSaveType() == 1) { - String path = ExcelPublicUtil.getWebRootPath(getSaveUrl( + String path = POIPublicUtil.getWebRootPath(getSaveUrl( excelParams.get(titleString), object)); File savefile = new File(path); if (!savefile.exists()) { @@ -354,10 +354,10 @@ public class ExcelImportServer { Row row, Map titlemap, String targetId, Map pictures, ImportParams params) throws Exception { - Collection collection = (Collection) ExcelPublicUtil.getMethod( + Collection collection = (Collection) POIPublicUtil.getMethod( param.getName(), object.getClass()).invoke(object, new Object[] {}); - Object entity = ExcelPublicUtil.createObject(param.getType(), targetId); + Object entity = POIPublicUtil.createObject(param.getType(), targetId); String picId; boolean isUsed = false;// 是否需要加上这个对象 for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) { @@ -436,10 +436,10 @@ public class ExcelImportServer { ExcelImportEntity excelEntity = null; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; - if (ExcelPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + if (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { continue; } - if (ExcelPublicUtil.isCollection(field.getType())) { + if (POIPublicUtil.isCollection(field.getType())) { // 集合对象设置属性 ExcelCollectionParams collection = new ExcelCollectionParams(); collection.setName(field.getName()); @@ -449,10 +449,10 @@ public class ExcelImportServer { Class clz = (Class) pt.getActualTypeArguments()[0]; collection.setType(clz); getExcelFieldList(targetId, - ExcelPublicUtil.getClassFields(clz), clz, temp, null); + POIPublicUtil.getClassFields(clz), clz, temp, null); collection.setExcelParams(temp); excelCollection.add(collection); - } else if (ExcelPublicUtil.isJavaClass(field)) { + } else if (POIPublicUtil.isJavaClass(field)) { addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, excelParams); } else { @@ -460,10 +460,10 @@ public class ExcelImportServer { if (getMethods != null) { newMethods.addAll(getMethods); } - newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + newMethods.add(POIPublicUtil.getMethod(field.getName(), pojoClass)); getAllExcelField(targetId, - ExcelPublicUtil.getClassFields(field.getType()), + POIPublicUtil.getClassFields(field.getType()), excelParams, excelCollection, field.getType(), newMethods); } @@ -476,10 +476,10 @@ public class ExcelImportServer { ExcelImportEntity excelEntity = null; for (int i = 0; i < fields.length; i++) { Field field = fields[i]; - if (ExcelPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { + if (POIPublicUtil.isNotUserExcelUserThis(null, field, targetId)) { continue; } - if (ExcelPublicUtil.isJavaClass(field)) { + if (POIPublicUtil.isJavaClass(field)) { addEntityToMap(targetId, field, excelEntity, pojoClass, getMethods, temp); } else { @@ -487,10 +487,10 @@ public class ExcelImportServer { if (getMethods != null) { newMethods.addAll(getMethods); } - newMethods.add(ExcelPublicUtil.getMethod(field.getName(), + newMethods.add(POIPublicUtil.getMethod(field.getName(), pojoClass, field.getType())); getExcelFieldList(targetId, - ExcelPublicUtil.getClassFields(field.getType()), + POIPublicUtil.getClassFields(field.getType()), field.getType(), temp, newMethods); } } @@ -559,7 +559,7 @@ public class ExcelImportServer { throws Exception { excelEntity.setName(getExcelName(excel.name(), targetId)); String fieldname = field.getName(); - excelEntity.setMethod(ExcelPublicUtil.getMethod(fieldname, pojoClass, + excelEntity.setMethod(POIPublicUtil.getMethod(fieldname, pojoClass, field.getType())); if (StringUtils.isEmpty(excel.importFormat())) { excelEntity.setFormat(excel.format()); diff --git a/easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java b/easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java similarity index 95% rename from easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java rename to easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java index 2a34299..75dd6d2 100644 --- a/easypoi-base/src/main/java/org/jeecgframework/poi/util/ExcelPublicUtil.java +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/util/POIPublicUtil.java @@ -15,11 +15,11 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; -public class ExcelPublicUtil { +public class POIPublicUtil { public static String getWebRootPath(String filePath) { // 这个path还是要测试的 - String path = ExcelPublicUtil.class.getClassLoader().getResource("") + String path = POIPublicUtil.class.getClassLoader().getResource("") .getPath() + filePath; path = path.replace("WEB-INF/classes/", ""); 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 new file mode 100644 index 0000000..cb6982e --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/WordExportUtil.java @@ -0,0 +1,28 @@ +package org.jeecgframework.poi.word; + +import java.util.Map; + +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.jeecgframework.poi.word.parse.ParseWord07; + +/** + * Word使用模板导出工具类 + * @author JueYue + * @date 2013-11-16 + * @version 1.0 + */ +public class WordExportUtil { + + /** + * 解析Word2007版本 + *@Author JueYue + *@date 2013-11-16 + *@param url 模板地址 + *@param map 解析数据源 + *@return + */ + public static XWPFDocument exportWord07(String url,Map map) throws Exception{ + return new ParseWord07().parseWord(url, 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 new file mode 100644 index 0000000..64bf9db --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/JeecgXWPFDocument.java @@ -0,0 +1,157 @@ +package org.jeecgframework.poi.word.entity; + +import java.io.InputStream; + +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlToken; +import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; +import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; +import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; + +/** + * 扩充document,修复图片插入失败问题问题 + * + * @author JueYue + * @date 2013-11-20 + * @version 1.0 + */ +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"); + } + +} 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 new file mode 100644 index 0000000..6c16e07 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/entity/WordImageEntity.java @@ -0,0 +1,67 @@ +package org.jeecgframework.poi.word.entity; +/** + * word导出,图片设置和图片信息 + * @author JueYue + * @date 2013-11-17 + * @version 1.0 + */ +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 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; + } + +} 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 new file mode 100644 index 0000000..3e62fc9 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/parse/ParseWord07.java @@ -0,0 +1,282 @@ +package org.jeecgframework.poi.word.parse; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.apache.poi.xwpf.usermodel.XWPFParagraph; +import org.apache.poi.xwpf.usermodel.XWPFRun; +import org.apache.poi.xwpf.usermodel.XWPFTable; +import org.apache.poi.xwpf.usermodel.XWPFTableCell; +import org.apache.poi.xwpf.usermodel.XWPFTableRow; +import org.jeecgframework.poi.cache.WordCache; +import org.jeecgframework.poi.word.entity.JeecgXWPFDocument; +import org.jeecgframework.poi.word.entity.WordImageEntity; +import org.jeecgframework.poi.word.util.ParseWordUtil; + +/** + * 解析07版的Word,替换文字,生成表格,生成图片 + * + * @author JueYue + * @date 2013-11-16 + * @version 1.0 + */ +@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; + } + + 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; + 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{ + table.removeRow(i);//删除这一行 + parseNextRowAndAddRow(table,i,(List) listobj); + } + }else{ + parseThisRow(cells,map); + } + } + } + + + /** + * 解析下一行,并且生成更多的行 + *@Author JueYue + *@date 2013-11-18 + *@param table + *@param listobj2 + */ + private 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 cells = currentRow.getTableCells(); + String[] params = new String[cells.size()]; + String text; + for (int i=0;i 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){ + 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(); + } + + } + + + + +} 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 new file mode 100644 index 0000000..48e9549 --- /dev/null +++ b/easypoi-base/src/main/java/org/jeecgframework/poi/word/util/ParseWordUtil.java @@ -0,0 +1,143 @@ +package org.jeecgframework.poi.word.util; + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Map; + +import javax.imageio.ImageIO; + +import org.apache.poi.xwpf.usermodel.XWPFDocument; +import org.jeecgframework.poi.util.POIPublicUtil; +import org.jeecgframework.poi.word.entity.WordImageEntity; + + +/** + * 解析公告类 + * @author JueYue + * @date 2014-7-24 + * @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){ + 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) : ""; + } + + /** + * 通过遍历过去对象值 + * + * @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; + } + + +} diff --git a/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties index f9af047..65e7c01 100644 --- a/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties +++ b/easypoi-base/target/classes/META-INF/maven/org.jeecgframework/easypoi-base/pom.properties @@ -1,5 +1,5 @@ #Generated by Maven Integration for Eclipse -#Thu Jul 24 22:34:43 CST 2014 +#Thu Jul 24 23:06:08 CST 2014 version=2.0.1 groupId=org.jeecgframework m2e.projectName=easypoi-base