Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.extractor;
  16. import java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.text.DateFormat;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.HashMap;
  23. import java.util.List;
  24. import java.util.Map;
  25. import java.util.Vector;
  26. import javax.xml.parsers.ParserConfigurationException;
  27. import javax.xml.transform.OutputKeys;
  28. import javax.xml.transform.Source;
  29. import javax.xml.transform.Transformer;
  30. import javax.xml.transform.TransformerException;
  31. import javax.xml.transform.TransformerFactory;
  32. import javax.xml.transform.dom.DOMSource;
  33. import javax.xml.transform.stream.StreamResult;
  34. import javax.xml.validation.Schema;
  35. import javax.xml.validation.SchemaFactory;
  36. import javax.xml.validation.Validator;
  37. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  38. import org.apache.poi.ss.usermodel.Cell;
  39. import org.apache.poi.ss.usermodel.DateUtil;
  40. import org.apache.poi.util.DocumentHelper;
  41. import org.apache.poi.xssf.usermodel.XSSFCell;
  42. import org.apache.poi.xssf.usermodel.XSSFMap;
  43. import org.apache.poi.xssf.usermodel.XSSFRow;
  44. import org.apache.poi.xssf.usermodel.XSSFSheet;
  45. import org.apache.poi.xssf.usermodel.XSSFTable;
  46. import org.apache.poi.xssf.usermodel.helpers.XSSFSingleXmlCell;
  47. import org.apache.poi.xssf.usermodel.helpers.XSSFXmlColumnPr;
  48. import org.openxmlformats.schemas.spreadsheetml.x2006.main.STXmlDataType;
  49. import org.w3c.dom.Document;
  50. import org.w3c.dom.Element;
  51. import org.w3c.dom.NamedNodeMap;
  52. import org.w3c.dom.Node;
  53. import org.w3c.dom.NodeList;
  54. import org.xml.sax.SAXException;
  55. /**
  56. *
  57. * Maps an XLSX to an XML according to one of the mapping defined.
  58. *
  59. *
  60. * The output XML Schema must respect this limitations:
  61. *
  62. * <ul>
  63. * <li> all mandatory elements and attributes must be mapped (enable validation to check this)</li>
  64. *
  65. * <li> no &lt;any&gt; in complex type/element declaration </li>
  66. * <li> no &lt;anyAttribute&gt; attributes declaration </li>
  67. * <li> no recursive structures: recursive structures can't be nested more than one level </li>
  68. * <li> no abstract elements: abstract complex types can be declared but must not be used in elements. </li>
  69. * <li> no mixed content: an element can't contain simple text and child element(s) together </li>
  70. * <li> no &lt;substitutionGroup&gt; in complex type/element declaration </li>
  71. * </ul>
  72. */
  73. public class XSSFExportToXml implements Comparator<String>{
  74. private XSSFMap map;
  75. /**
  76. * Creates a new exporter and sets the mapping to be used when generating the XML output document
  77. *
  78. * @param map the mapping rule to be used
  79. */
  80. public XSSFExportToXml(XSSFMap map) {
  81. this.map = map;
  82. }
  83. /**
  84. *
  85. * Exports the data in an XML stream
  86. *
  87. * @param os OutputStream in which will contain the output XML
  88. * @param validate if true, validates the XML againts the XML Schema
  89. * @throws SAXException
  90. * @throws TransformerException
  91. * @throws ParserConfigurationException
  92. */
  93. public void exportToXML(OutputStream os, boolean validate) throws SAXException, ParserConfigurationException, TransformerException {
  94. exportToXML(os, "UTF-8", validate);
  95. }
  96. /**
  97. * Exports the data in an XML stream
  98. *
  99. * @param os OutputStream in which will contain the output XML
  100. * @param encoding the output charset encoding
  101. * @param validate if true, validates the XML againts the XML Schema
  102. * @throws SAXException
  103. * @throws ParserConfigurationException
  104. * @throws TransformerException
  105. * @throws InvalidFormatException
  106. */
  107. public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, ParserConfigurationException, TransformerException{
  108. List<XSSFSingleXmlCell> singleXMLCells = map.getRelatedSingleXMLCell();
  109. List<XSSFTable> tables = map.getRelatedTables();
  110. String rootElement = map.getCtMap().getRootElement();
  111. Document doc = DocumentHelper.createDocument();
  112. Element root = null;
  113. if (isNamespaceDeclared()) {
  114. root=doc.createElementNS(getNamespace(),rootElement);
  115. } else {
  116. root = doc.createElementNS("", rootElement);
  117. }
  118. doc.appendChild(root);
  119. List<String> xpaths = new Vector<String>();
  120. Map<String,XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<String,XSSFSingleXmlCell>();
  121. Map<String,XSSFTable> tableMappings = new HashMap<String,XSSFTable>();
  122. for(XSSFSingleXmlCell simpleXmlCell : singleXMLCells) {
  123. xpaths.add(simpleXmlCell.getXpath());
  124. singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
  125. }
  126. for(XSSFTable table : tables) {
  127. String commonXPath = table.getCommonXpath();
  128. xpaths.add(commonXPath);
  129. tableMappings.put(commonXPath, table);
  130. }
  131. Collections.sort(xpaths,this);
  132. for(String xpath : xpaths) {
  133. XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
  134. XSSFTable table = tableMappings.get(xpath);
  135. if (!xpath.matches(".*\\[.*")) {
  136. // Exports elements and attributes mapped with simpleXmlCell
  137. if (simpleXmlCell!=null) {
  138. XSSFCell cell = simpleXmlCell.getReferencedCell();
  139. if (cell!=null) {
  140. Node currentNode = getNodeByXPath(xpath,doc.getFirstChild(),doc,false);
  141. STXmlDataType.Enum dataType = simpleXmlCell.getXmlDataType();
  142. mapCellOnNode(cell,currentNode,dataType);
  143. //remove nodes which are empty in order to keep the output xml valid
  144. if("".equals(currentNode.getTextContent()) && currentNode.getParentNode() != null) {
  145. currentNode.getParentNode().removeChild(currentNode);
  146. }
  147. }
  148. }
  149. // Exports elements and attributes mapped with tables
  150. if (table!=null) {
  151. List<XSSFXmlColumnPr> tableColumns = table.getXmlColumnPrs();
  152. XSSFSheet sheet = table.getXSSFSheet();
  153. int startRow = table.getStartCellReference().getRow();
  154. // In mappings created with Microsoft Excel the first row contains the table header and must be skipped
  155. startRow +=1;
  156. int endRow = table.getEndCellReference().getRow();
  157. for(int i = startRow; i<= endRow; i++) {
  158. XSSFRow row = sheet.getRow(i);
  159. Node tableRootNode = getNodeByXPath(table.getCommonXpath(),doc.getFirstChild(),doc,true);
  160. short startColumnIndex = table.getStartCellReference().getCol();
  161. for(int j = startColumnIndex; j<= table.getEndCellReference().getCol();j++) {
  162. XSSFCell cell = row.getCell(j);
  163. if (cell!=null) {
  164. XSSFXmlColumnPr pointer = tableColumns.get(j-startColumnIndex);
  165. String localXPath = pointer.getLocalXPath();
  166. Node currentNode = getNodeByXPath(localXPath,tableRootNode,doc,false);
  167. STXmlDataType.Enum dataType = pointer.getXmlDataType();
  168. mapCellOnNode(cell,currentNode,dataType);
  169. }
  170. }
  171. }
  172. }
  173. } else {
  174. // TODO: implement filtering management in xpath
  175. }
  176. }
  177. boolean isValid = true;
  178. if (validate) {
  179. isValid =isValid(doc);
  180. }
  181. if (isValid) {
  182. /////////////////
  183. //Output the XML
  184. //set up a transformer
  185. TransformerFactory transfac = TransformerFactory.newInstance();
  186. Transformer trans = transfac.newTransformer();
  187. trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  188. trans.setOutputProperty(OutputKeys.INDENT, "yes");
  189. trans.setOutputProperty(OutputKeys.ENCODING, encoding);
  190. //create string from xml tree
  191. StreamResult result = new StreamResult(os);
  192. DOMSource source = new DOMSource(doc);
  193. trans.transform(source, result);
  194. }
  195. }
  196. /**
  197. * Validate the generated XML against the XML Schema associated with the XSSFMap
  198. *
  199. * @param xml the XML to validate
  200. * @return true, if document is valid
  201. */
  202. private boolean isValid(Document xml) throws SAXException{
  203. try{
  204. String language = "http://www.w3.org/2001/XMLSchema";
  205. SchemaFactory factory = SchemaFactory.newInstance(language);
  206. Source source = new DOMSource(map.getSchema());
  207. Schema schema = factory.newSchema(source);
  208. Validator validator = schema.newValidator();
  209. validator.validate(new DOMSource(xml));
  210. //if no exceptions where raised, the document is valid
  211. return true;
  212. } catch(IOException e) {
  213. e.printStackTrace();
  214. }
  215. return false;
  216. }
  217. private void mapCellOnNode(XSSFCell cell, Node node, STXmlDataType.Enum outputDataType) {
  218. String value ="";
  219. switch (cell.getCellType()) {
  220. case XSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break;
  221. case XSSFCell.CELL_TYPE_BOOLEAN: value += cell.getBooleanCellValue(); break;
  222. case XSSFCell.CELL_TYPE_ERROR: value = cell.getErrorCellString(); break;
  223. case XSSFCell.CELL_TYPE_FORMULA:
  224. if (cell.getCachedFormulaResultType() == Cell.CELL_TYPE_STRING) {
  225. value = cell.getStringCellValue();
  226. } else {
  227. if (DateUtil.isCellDateFormatted(cell)) {
  228. value = getFormattedDate(cell);
  229. } else {
  230. value += cell.getNumericCellValue();
  231. }
  232. }
  233. break;
  234. case XSSFCell.CELL_TYPE_NUMERIC:
  235. if (DateUtil.isCellDateFormatted(cell)) {
  236. value = getFormattedDate(cell);
  237. } else {
  238. value += cell.getRawValue();
  239. }
  240. break;
  241. default: ;
  242. }
  243. if (node instanceof Element) {
  244. Element currentElement = (Element) node;
  245. currentElement.setTextContent(value);
  246. } else {
  247. node.setNodeValue(value);
  248. }
  249. }
  250. private String removeNamespace(String elementName) {
  251. return elementName.matches(".*:.*")?elementName.split(":")[1]:elementName;
  252. }
  253. private String getFormattedDate(XSSFCell cell) {
  254. DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  255. return sdf.format(cell.getDateCellValue());
  256. }
  257. private Node getNodeByXPath(String xpath,Node rootNode,Document doc,boolean createMultipleInstances) {
  258. String[] xpathTokens = xpath.split("/");
  259. Node currentNode =rootNode;
  260. // The first token is empty, the second is the root node
  261. for(int i =2; i<xpathTokens.length;i++) {
  262. String axisName = removeNamespace(xpathTokens[i]);
  263. if (!axisName.startsWith("@")) {
  264. NodeList list =currentNode.getChildNodes();
  265. Node selectedNode = null;
  266. if (!(createMultipleInstances && i==xpathTokens.length-1) ) {
  267. // select the last child node only if we need to map to a single cell
  268. selectedNode = selectNode(axisName, list);
  269. }
  270. if (selectedNode==null) {
  271. selectedNode = createElement(doc, currentNode, axisName);
  272. }
  273. currentNode = selectedNode;
  274. } else {
  275. Node attribute = createAttribute(doc, currentNode, axisName);
  276. currentNode = attribute;
  277. }
  278. }
  279. return currentNode;
  280. }
  281. private Node createAttribute(Document doc, Node currentNode, String axisName) {
  282. String attributeName = axisName.substring(1);
  283. NamedNodeMap attributesMap = currentNode.getAttributes();
  284. Node attribute = attributesMap.getNamedItem(attributeName);
  285. if (attribute==null) {
  286. attribute = doc.createAttributeNS("", attributeName);
  287. attributesMap.setNamedItem(attribute);
  288. }
  289. return attribute;
  290. }
  291. private Node createElement(Document doc, Node currentNode, String axisName) {
  292. Node selectedNode;
  293. if (isNamespaceDeclared()) {
  294. selectedNode =doc.createElementNS(getNamespace(),axisName);
  295. } else {
  296. selectedNode = doc.createElementNS("", axisName);
  297. }
  298. currentNode.appendChild(selectedNode);
  299. return selectedNode;
  300. }
  301. private Node selectNode(String axisName, NodeList list) {
  302. Node selectedNode = null;
  303. for(int j=0;j<list.getLength();j++) {
  304. Node node = list.item(j);
  305. if (node.getNodeName().equals(axisName)) {
  306. selectedNode=node;
  307. break;
  308. }
  309. }
  310. return selectedNode;
  311. }
  312. private boolean isNamespaceDeclared() {
  313. String schemaNamespace = getNamespace();
  314. return schemaNamespace!=null && !schemaNamespace.equals("");
  315. }
  316. private String getNamespace() {
  317. return map.getCTSchema().getNamespace();
  318. }
  319. /**
  320. * Compares two xpaths to define an ordering according to the XML Schema
  321. *
  322. */
  323. @Override
  324. public int compare(String leftXpath, String rightXpath) {
  325. Node xmlSchema = map.getSchema();
  326. String[] leftTokens = leftXpath.split("/");
  327. String[] rightTokens = rightXpath.split("/");
  328. int minLenght = leftTokens.length< rightTokens.length? leftTokens.length : rightTokens.length;
  329. Node localComplexTypeRootNode = xmlSchema;
  330. for(int i =1;i <minLenght; i++) {
  331. String leftElementName =leftTokens[i];
  332. String rightElementName = rightTokens[i];
  333. if (leftElementName.equals(rightElementName)) {
  334. Node complexType = getComplexTypeForElement(leftElementName, xmlSchema,localComplexTypeRootNode);
  335. localComplexTypeRootNode = complexType;
  336. } else {
  337. int leftIndex = indexOfElementInComplexType(leftElementName,localComplexTypeRootNode);
  338. int rightIndex = indexOfElementInComplexType(rightElementName,localComplexTypeRootNode);
  339. if (leftIndex!=-1 && rightIndex!=-1) {
  340. if ( leftIndex < rightIndex) {
  341. return -1;
  342. }if ( leftIndex > rightIndex) {
  343. return 1;
  344. }
  345. } else {
  346. // NOTE: the xpath doesn't match correctly in the schema
  347. }
  348. }
  349. }
  350. return 0;
  351. }
  352. private int indexOfElementInComplexType(String elementName,Node complexType) {
  353. NodeList list = complexType.getChildNodes();
  354. int indexOf = -1;
  355. for(int i=0; i< list.getLength();i++) {
  356. Node node = list.item(i);
  357. if (node instanceof Element) {
  358. if (node.getLocalName().equals("element")) {
  359. Node element = getNameOrRefElement(node);
  360. if (element.getNodeValue().equals(removeNamespace(elementName))) {
  361. indexOf = i;
  362. break;
  363. }
  364. }
  365. }
  366. }
  367. return indexOf;
  368. }
  369. private Node getNameOrRefElement(Node node) {
  370. Node returnNode = node.getAttributes().getNamedItem("name");
  371. if(returnNode != null) {
  372. return returnNode;
  373. }
  374. return node.getAttributes().getNamedItem("ref");
  375. }
  376. private Node getComplexTypeForElement(String elementName,Node xmlSchema,Node localComplexTypeRootNode) {
  377. String elementNameWithoutNamespace = removeNamespace(elementName);
  378. String complexTypeName = getComplexTypeNameFromChildren(localComplexTypeRootNode, elementNameWithoutNamespace);
  379. // Note: we expect that all the complex types are defined at root level
  380. Node complexTypeNode = null;
  381. if (!"".equals(complexTypeName)) {
  382. complexTypeNode = getComplexTypeNodeFromSchemaChildren(xmlSchema, complexTypeNode, complexTypeName);
  383. }
  384. return complexTypeNode;
  385. }
  386. private String getComplexTypeNameFromChildren(Node localComplexTypeRootNode,
  387. String elementNameWithoutNamespace) {
  388. NodeList list = localComplexTypeRootNode.getChildNodes();
  389. String complexTypeName = "";
  390. for(int i=0; i< list.getLength();i++) {
  391. Node node = list.item(i);
  392. if ( node instanceof Element) {
  393. if (node.getLocalName().equals("element")) {
  394. Node nameAttribute = getNameOrRefElement(node);
  395. if (nameAttribute.getNodeValue().equals(elementNameWithoutNamespace)) {
  396. Node complexTypeAttribute = node.getAttributes().getNamedItem("type");
  397. if (complexTypeAttribute!=null) {
  398. complexTypeName = complexTypeAttribute.getNodeValue();
  399. break;
  400. }
  401. }
  402. }
  403. }
  404. }
  405. return complexTypeName;
  406. }
  407. private Node getComplexTypeNodeFromSchemaChildren(Node xmlSchema, Node complexTypeNode,
  408. String complexTypeName) {
  409. NodeList complexTypeList = xmlSchema.getChildNodes();
  410. for(int i=0; i< complexTypeList.getLength();i++) {
  411. Node node = complexTypeList.item(i);
  412. if ( node instanceof Element) {
  413. if (node.getLocalName().equals("complexType")) {
  414. Node nameAttribute = getNameOrRefElement(node);
  415. if (nameAttribute.getNodeValue().equals(complexTypeName)) {
  416. NodeList complexTypeChildList =node.getChildNodes();
  417. for(int j=0; j<complexTypeChildList.getLength();j++) {
  418. Node sequence = complexTypeChildList.item(j);
  419. if ( sequence instanceof Element) {
  420. if (sequence.getLocalName().equals("sequence") || sequence.getLocalName().equals("all")) {
  421. complexTypeNode = sequence;
  422. break;
  423. }
  424. }
  425. }
  426. if (complexTypeNode!=null) {
  427. break;
  428. }
  429. }
  430. }
  431. }
  432. }
  433. return complexTypeNode;
  434. }
  435. }