use of org.apache.poi.xssf.usermodel.XSSFTable in project poi by apache.
the class CreateTable method main.
public static void main(String[] args) throws IOException {
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
//Create
XSSFTable table = sheet.createTable();
table.setDisplayName("Test");
CTTable cttable = table.getCTTable();
//Style configurations
CTTableStyleInfo style = cttable.addNewTableStyleInfo();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
//Set which area the table should be placed in
AreaReference reference = new AreaReference(new CellReference(0, 0), new CellReference(2, 2));
cttable.setRef(reference.formatAsString());
cttable.setId(1);
cttable.setName("Test");
cttable.setTotalsRowCount(1);
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(3);
CTTableColumn column;
XSSFRow row;
XSSFCell cell;
for (int i = 0; i < 3; i++) {
//Create column
column = columns.addNewTableColumn();
column.setName("Column");
column.setId(i + 1);
//Create row
row = sheet.createRow(i);
for (int j = 0; j < 3; j++) {
//Create cell
cell = row.createCell(j);
if (i == 0) {
cell.setCellValue("Column" + j);
} else {
cell.setCellValue("0");
}
}
}
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
use of org.apache.poi.xssf.usermodel.XSSFTable in project poi by apache.
the class TestStructuredReferences method testTableFormulas.
@Test
public void testTableFormulas() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("StructuredReferences.xlsx");
try {
final FormulaEvaluator eval = new XSSFFormulaEvaluator(wb);
final XSSFSheet tableSheet = wb.getSheet("Table");
final XSSFSheet formulaSheet = wb.getSheet("Formulas");
confirm(eval, tableSheet.getRow(5).getCell(0), 49);
confirm(eval, formulaSheet.getRow(0).getCell(0), 209);
confirm(eval, formulaSheet.getRow(1).getCell(0), "one");
// test changing a table value, to see if the caches are properly cleared
// Issue 59814
// this test passes before the fix for 59814
tableSheet.getRow(1).getCell(1).setCellValue("ONEA");
confirm(eval, formulaSheet.getRow(1).getCell(0), "ONEA");
// test adding a row to a table, issue 59814
Row newRow = tableSheet.getRow(7);
if (newRow == null)
newRow = tableSheet.createRow(7);
newRow.createCell(0, CellType.FORMULA).setCellFormula("\\_Prime.1[[#This Row],[@Number]]*\\_Prime.1[[#This Row],[@Number]]");
newRow.createCell(1, CellType.STRING).setCellValue("thirteen");
newRow.createCell(2, CellType.NUMERIC).setCellValue(13);
// update Table
final XSSFTable table = wb.getTable("\\_Prime.1");
final AreaReference newArea = new AreaReference(table.getStartCellReference(), new CellReference(table.getEndRowIndex() + 1, table.getEndColIndex()));
String newAreaStr = newArea.formatAsString();
table.getCTTable().setRef(newAreaStr);
table.getCTTable().getAutoFilter().setRef(newAreaStr);
table.updateHeaders();
table.updateReferences();
// these fail before the fix for 59814
confirm(eval, tableSheet.getRow(7).getCell(0), 13 * 13);
confirm(eval, formulaSheet.getRow(0).getCell(0), 209 + 13 * 13);
} finally {
wb.close();
}
}
use of org.apache.poi.xssf.usermodel.XSSFTable in project poi by apache.
the class XSSFImportFromXML method importFromXML.
/**
* Imports an XML into the XLSX using the Custom XML mapping defined
*
* @param xmlInputString the XML to import
* @throws SAXException if error occurs during XML parsing
* @throws XPathExpressionException if error occurs during XML navigation
* @throws ParserConfigurationException if there are problems with XML parser configuration
* @throws IOException if there are problems reading the input string
*/
public void importFromXML(String xmlInputString) throws SAXException, XPathExpressionException, IOException {
DocumentBuilder builder = DocumentHelper.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(xmlInputString.trim())));
List<XSSFSingleXmlCell> singleXmlCells = _map.getRelatedSingleXMLCell();
List<XSSFTable> tables = _map.getRelatedTables();
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
// Setting namespace context to XPath
// Assuming that the namespace prefix in the mapping xpath is the
// same as the one used in the document
xpath.setNamespaceContext(new DefaultNamespaceContext(doc));
for (XSSFSingleXmlCell singleXmlCell : singleXmlCells) {
STXmlDataType.Enum xmlDataType = singleXmlCell.getXmlDataType();
String xpathString = singleXmlCell.getXpath();
Node result = (Node) xpath.evaluate(xpathString, doc, XPathConstants.NODE);
// result can be null if value is optional (xsd:minOccurs=0), see bugzilla 55864
if (result != null) {
String textContent = result.getTextContent();
logger.log(POILogger.DEBUG, "Extracting with xpath " + xpathString + " : value is '" + textContent + "'");
XSSFCell cell = singleXmlCell.getReferencedCell();
logger.log(POILogger.DEBUG, "Setting '" + textContent + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " + cell.getSheet().getSheetName());
setCellValue(textContent, cell, xmlDataType);
}
}
for (XSSFTable table : tables) {
String commonXPath = table.getCommonXpath();
NodeList result = (NodeList) xpath.evaluate(commonXPath, doc, XPathConstants.NODESET);
// the first row contains the table header
int rowOffset = table.getStartCellReference().getRow() + 1;
int columnOffset = table.getStartCellReference().getCol() - 1;
for (int i = 0; i < result.getLength(); i++) {
// TODO: implement support for denormalized XMLs (see
// OpenOffice part 4: chapter 3.5.1.7)
Node singleNode = result.item(i).cloneNode(true);
for (XSSFXmlColumnPr xmlColumnPr : table.getXmlColumnPrs()) {
int localColumnId = (int) xmlColumnPr.getId();
int rowId = rowOffset + i;
int columnId = columnOffset + localColumnId;
String localXPath = xmlColumnPr.getLocalXPath();
localXPath = localXPath.substring(localXPath.substring(1).indexOf('/') + 2);
// TODO: convert the data to the cell format
String value = (String) xpath.evaluate(localXPath, singleNode, XPathConstants.STRING);
logger.log(POILogger.DEBUG, "Extracting with xpath " + localXPath + " : value is '" + value + "'");
XSSFRow row = table.getXSSFSheet().getRow(rowId);
if (row == null) {
row = table.getXSSFSheet().createRow(rowId);
}
XSSFCell cell = row.getCell(columnId);
if (cell == null) {
cell = row.createCell(columnId);
}
logger.log(POILogger.DEBUG, "Setting '" + value + "' to cell " + cell.getColumnIndex() + "-" + cell.getRowIndex() + " in sheet " + table.getXSSFSheet().getSheetName());
setCellValue(value, cell, xmlColumnPr.getXmlDataType());
}
}
}
}
use of org.apache.poi.xssf.usermodel.XSSFTable in project poi by apache.
the class XSSFExportToXml method exportToXML.
/**
* Exports the data in an XML stream
*
* @param os OutputStream in which will contain the output XML
* @param encoding the output charset encoding
* @param validate if true, validates the XML against the XML Schema
* @throws SAXException If validating the document fails
* @throws TransformerException If transforming the document fails
*/
public void exportToXML(OutputStream os, String encoding, boolean validate) throws SAXException, TransformerException {
List<XSSFSingleXmlCell> singleXMLCells = map.getRelatedSingleXMLCell();
List<XSSFTable> tables = map.getRelatedTables();
String rootElement = map.getCtMap().getRootElement();
Document doc = DocumentHelper.createDocument();
final Element root;
if (isNamespaceDeclared()) {
root = doc.createElementNS(getNamespace(), rootElement);
} else {
root = doc.createElementNS("", rootElement);
}
doc.appendChild(root);
List<String> xpaths = new Vector<String>();
Map<String, XSSFSingleXmlCell> singleXmlCellsMappings = new HashMap<String, XSSFSingleXmlCell>();
Map<String, XSSFTable> tableMappings = new HashMap<String, XSSFTable>();
for (XSSFSingleXmlCell simpleXmlCell : singleXMLCells) {
xpaths.add(simpleXmlCell.getXpath());
singleXmlCellsMappings.put(simpleXmlCell.getXpath(), simpleXmlCell);
}
for (XSSFTable table : tables) {
String commonXPath = table.getCommonXpath();
xpaths.add(commonXPath);
tableMappings.put(commonXPath, table);
}
Collections.sort(xpaths, this);
for (String xpath : xpaths) {
XSSFSingleXmlCell simpleXmlCell = singleXmlCellsMappings.get(xpath);
XSSFTable table = tableMappings.get(xpath);
if (!xpath.matches(".*\\[.*")) {
// Exports elements and attributes mapped with simpleXmlCell
if (simpleXmlCell != null) {
XSSFCell cell = simpleXmlCell.getReferencedCell();
if (cell != null) {
Node currentNode = getNodeByXPath(xpath, doc.getFirstChild(), doc, false);
mapCellOnNode(cell, currentNode);
//remove nodes which are empty in order to keep the output xml valid
if ("".equals(currentNode.getTextContent()) && currentNode.getParentNode() != null) {
currentNode.getParentNode().removeChild(currentNode);
}
}
}
// Exports elements and attributes mapped with tables
if (table != null) {
List<XSSFXmlColumnPr> tableColumns = table.getXmlColumnPrs();
XSSFSheet sheet = table.getXSSFSheet();
int startRow = table.getStartCellReference().getRow();
// In mappings created with Microsoft Excel the first row contains the table header and must be skipped
startRow += 1;
int endRow = table.getEndCellReference().getRow();
for (int i = startRow; i <= endRow; i++) {
XSSFRow row = sheet.getRow(i);
Node tableRootNode = getNodeByXPath(table.getCommonXpath(), doc.getFirstChild(), doc, true);
short startColumnIndex = table.getStartCellReference().getCol();
for (int j = startColumnIndex; j <= table.getEndCellReference().getCol(); j++) {
XSSFCell cell = row.getCell(j);
if (cell != null) {
XSSFXmlColumnPr pointer = tableColumns.get(j - startColumnIndex);
String localXPath = pointer.getLocalXPath();
Node currentNode = getNodeByXPath(localXPath, tableRootNode, doc, false);
mapCellOnNode(cell, currentNode);
}
}
}
}
}
/*else {
// TODO: implement filtering management in xpath
}*/
}
boolean isValid = true;
if (validate) {
isValid = isValid(doc);
}
if (isValid) {
/////////////////
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.ENCODING, encoding);
//create string from xml tree
StreamResult result = new StreamResult(os);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
}
}
Aggregations