List of usage examples for org.apache.poi.ss.usermodel Sheet createRow
Row createRow(int rownum);
From source file:com.quanticate.opensource.spreadsheetexcerpt.excerpt.TestPOIExcerpter.java
License:Apache License
@Test public void excerptGoesReadOnly() throws Exception { for (Workbook wb : new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() }) { FormulaEvaluator eval = wb.getCreationHelper().createFormulaEvaluator(); Sheet s = wb.createSheet("Test"); // Numeric formulas Row r1 = s.createRow(0); Cell c1 = r1.createCell(0);//from www . j av a 2 s . c o m Cell c2 = r1.createCell(1); Cell c3 = r1.createCell(2); Cell c4 = r1.createCell(3); c1.setCellValue(1); c2.setCellValue(2); c3.setCellFormula("A1+B1"); c4.setCellFormula("(A1+B1)*B1"); // Strings, booleans and errors Row r2 = s.createRow(1); Cell c21 = r2.createCell(0); Cell c22 = r2.createCell(1); Cell c23 = r2.createCell(2); Cell c24 = r2.createCell(3); c21.setCellValue("Testing"); c22.setCellFormula("CONCATENATE(A2,A2)"); c23.setCellFormula("FALSE()"); c24.setCellFormula("A1/0"); // Ensure the formulas are current eval.evaluateAll(); // Run the excerpt File tmp = File.createTempFile("test", ".xls"); wb.write(new FileOutputStream(tmp)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); excerpter.excerpt(new int[] { 0 }, tmp, baos); // Check Workbook newwb = WorkbookFactory.create(new ByteArrayInputStream(baos.toByteArray())); assertEquals(1, newwb.getNumberOfSheets()); s = newwb.getSheetAt(0); r1 = s.getRow(0); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(0).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(1).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(2).getCellType()); assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(3).getCellType()); assertEquals(1.0, s.getRow(0).getCell(0).getNumericCellValue(), 0.001); assertEquals(2.0, s.getRow(0).getCell(1).getNumericCellValue(), 0.001); assertEquals(3.0, s.getRow(0).getCell(2).getNumericCellValue(), 0.001); assertEquals(6.0, s.getRow(0).getCell(3).getNumericCellValue(), 0.001); r2 = s.getRow(1); assertEquals(Cell.CELL_TYPE_STRING, r2.getCell(0).getCellType()); assertEquals(Cell.CELL_TYPE_STRING, r2.getCell(1).getCellType()); assertEquals(Cell.CELL_TYPE_BOOLEAN, r2.getCell(2).getCellType()); assertEquals(Cell.CELL_TYPE_BLANK, r2.getCell(3).getCellType()); assertEquals("Testing", s.getRow(1).getCell(0).getStringCellValue()); assertEquals("TestingTesting", s.getRow(1).getCell(1).getStringCellValue()); assertEquals(false, s.getRow(1).getCell(2).getBooleanCellValue()); } }
From source file:com.quanticate.opensource.spreadsheetexcerpt.excerpt.TestPOIExcerpter.java
License:Apache License
@Test public void excerptRemovesUnUsed() throws Exception { String[] names = new String[] { "a", "b", "ccc", "dddd", "e", "f", "gg" }; for (Workbook wb : new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() }) { // Create some dummy content for (String sn : names) { Sheet s = wb.createSheet(sn); s.createRow(0).createCell(0).setCellValue(sn); }//from www.ja v a2 s. c o m // Excerpt by index File tmp = File.createTempFile("test", ".xls"); wb.write(new FileOutputStream(tmp)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int[] excI = new int[] { 0, 1, 2, 4, 5 }; excerpter.excerpt(excI, tmp, baos); // Check Workbook newwb = WorkbookFactory.create(new ByteArrayInputStream(baos.toByteArray())); assertEquals(5, newwb.getNumberOfSheets()); assertEquals(names[excI[0]], newwb.getSheetName(0)); assertEquals(names[excI[1]], newwb.getSheetName(1)); assertEquals(names[excI[2]], newwb.getSheetName(2)); assertEquals(names[excI[3]], newwb.getSheetName(3)); assertEquals(names[excI[4]], newwb.getSheetName(4)); assertEquals(names[excI[0]], newwb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); assertEquals(names[excI[1]], newwb.getSheetAt(1).getRow(0).getCell(0).getStringCellValue()); assertEquals(names[excI[2]], newwb.getSheetAt(2).getRow(0).getCell(0).getStringCellValue()); assertEquals(names[excI[3]], newwb.getSheetAt(3).getRow(0).getCell(0).getStringCellValue()); assertEquals(names[excI[4]], newwb.getSheetAt(4).getRow(0).getCell(0).getStringCellValue()); // Excerpt by name String[] excN = new String[] { "b", "ccc", "f", "gg" }; baos = new ByteArrayOutputStream(); excerpter.excerpt(excN, tmp, baos); newwb = WorkbookFactory.create(new ByteArrayInputStream(baos.toByteArray())); assertEquals(4, newwb.getNumberOfSheets()); assertEquals(excN[0], newwb.getSheetName(0)); assertEquals(excN[1], newwb.getSheetName(1)); assertEquals(excN[2], newwb.getSheetName(2)); assertEquals(excN[3], newwb.getSheetName(3)); assertEquals(excN[0], newwb.getSheetAt(0).getRow(0).getCell(0).getStringCellValue()); assertEquals(excN[1], newwb.getSheetAt(1).getRow(0).getCell(0).getStringCellValue()); assertEquals(excN[2], newwb.getSheetAt(2).getRow(0).getCell(0).getStringCellValue()); assertEquals(excN[3], newwb.getSheetAt(3).getRow(0).getCell(0).getStringCellValue()); // Can't excerpt by invalid index try { excerpter.excerpt(new int[] { 0, 10 }, tmp, null); fail(); } catch (IllegalArgumentException e) { } // Can't excerpt by invalid name try { excerpter.excerpt(new String[] { "a", "invalid" }, tmp, null); fail(); } catch (IllegalArgumentException e) { } } }
From source file:com.r573.enfili.common.doc.spreadsheet.SpreadsheetHelper.java
License:Apache License
/** * Creates a XSSFWorkbook with 1 default sheet "Sheet1" and returns the Worksheet * This is for simple temporary spreadsheets for calculation purpose * // w ww . j a va 2 s.c o m * @return */ public static Sheet createSimpleWorksheet(int numCols, int numRows) { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); for (int i = 0; i < numRows; i++) { Row row = sheet.createRow(i); for (int j = 0; j < numCols; j++) { row.createCell(j); } } return sheet; }
From source file:com.rapidminer.operator.io.ExcelExampleSetWriter.java
License:Open Source License
/** * Writes the provided {@link ExampleSet} to a XLSX formatted data sheet. * * @param wb/* www.j av a 2 s . com*/ * the workbook to use * @param sheet * the excel sheet to write to. * @param dateFormat * a string which describes the format used for dates. * @param numberFormat * a string which describes the format used for numbers. * @param exampleSet * the exampleSet to write * @param op * needed for checkForStop * @throws ProcessStoppedException * if the process was stopped by the user. * @throws WriteException */ private static void writeXLSXDataSheet(SXSSFWorkbook wb, Sheet sheet, String dateFormat, String numberFormat, ExampleSet exampleSet, Operator op) throws WriteException, ProcessStoppedException { Font headerFont = wb.createFont(); headerFont.setBold(true); CellStyle headerStyle = wb.createCellStyle(); headerStyle.setFont(headerFont); // create the header Iterator<Attribute> a = exampleSet.getAttributes().allAttributes(); int columnCounter = 0; int rowCounter = 0; Row headerRow = sheet.createRow(rowCounter); while (a.hasNext()) { Attribute attribute = a.next(); Cell headerCell = headerRow.createCell(columnCounter); headerCell.setCellValue(attribute.getName()); headerCell.setCellStyle(headerStyle); columnCounter++; } rowCounter++; // body font Font bodyFont = wb.createFont(); bodyFont.setBold(false); CreationHelper createHelper = wb.getCreationHelper(); // number format CellStyle numericalStyle = wb.createCellStyle(); numericalStyle.setDataFormat(createHelper.createDataFormat().getFormat(numberFormat)); numericalStyle.setFont(bodyFont); // date format CellStyle dateStyle = wb.createCellStyle(); dateStyle.setDataFormat(createHelper.createDataFormat().getFormat(dateFormat)); dateStyle.setFont(bodyFont); // create nominal cell style CellStyle nominalStyle = wb.createCellStyle(); nominalStyle.setFont(bodyFont); // fill body for (Example example : exampleSet) { // create new row Row bodyRow = sheet.createRow(rowCounter); // iterate over attributes and save examples a = exampleSet.getAttributes().allAttributes(); columnCounter = 0; while (a.hasNext()) { Attribute attribute = a.next(); Cell currentCell = bodyRow.createCell(columnCounter); if (!Double.isNaN(example.getValue(attribute))) { if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.DATE_TIME)) { Date dateValue = example.getDateValue(attribute); currentCell.setCellValue(dateValue); currentCell.setCellStyle(dateStyle); } else if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.NUMERICAL)) { double numericalValue = example.getNumericalValue(attribute); currentCell.setCellValue(numericalValue); currentCell.setCellStyle(numericalStyle); } else { currentCell.setCellValue( stripIfNecessary(replaceForbiddenChars(example.getValueAsString(attribute)))); currentCell.setCellStyle(nominalStyle); } } columnCounter++; } rowCounter++; // checkForStop every 100 examples if (op != null && rowCounter % 100 == 0) { op.checkForStop(); } } }
From source file:com.rarediscovery.services.logic.Functions.java
private static void addContent(Sheet sheet, // Sheet to be updated String[] columnHeaders, // Selected columns final Models models, // Available models in memory final DefaultListModel reportAttributes) // List of attributes selected to be reported { // Create Headers Row header = sheet.createRow((short) 0); header.createCell(0).setCellValue("Index"); header.createCell(1).setCellValue("Component Name"); for (int i = 0; i < columnHeaders.length; i++) { header.createCell(2 + i).setCellValue(columnHeaders[i]); }/* w w w .ja va 2 s .c om*/ int i = 1; Enumeration<String> ram = reportAttributes.elements(); while (ram.hasMoreElements()) { Row row = sheet.createRow(i); row.createCell(0).setCellValue("" + i); String component = ram.nextElement(); row.createCell(1).setCellValue(component); int k = 0; for (String modelName : columnHeaders) { row.createCell(2 + k).setCellValue(models.get(modelName).get(component)); k++; } i++; } }
From source file:com.rarediscovery.services.logic.WorkPad.java
/** * //from w w w . j av a 2 s . com * Add a column of data to a worksheet * * @param sheetName * @param dataArray * * @param startingRow * @param dataColumn */ public void addColumnData(String sheetName, String[] dataArray, int startingRow, int dataColumn) { Sheet s = addWorksheet(sheetName); CellStyle style = applySelectedStyle(); for (int r = 0; r < dataArray.length; r++) { Row row = null; // When item requested is out of range of available rows if (s.getLastRowNum() < startingRow + r) { row = s.createRow(startingRow + r); } else { row = s.getRow(startingRow + r); } row.createCell(dataColumn).setCellValue(dataArray[r]); row.setRowStyle(style); } }
From source file:com.rarediscovery.services.logic.WorkPad.java
public void addRowData(String sheetName, String[] dataArray, int rowIndex, int column) { Sheet s = addWorksheet(sheetName); Row row = null;/*from w ww .jav a 2 s . co m*/ // When item requested is out of range of available rows if (s.getLastRowNum() > rowIndex) { row = s.getRow(rowIndex); } else { row = s.createRow(rowIndex); } CellStyle style = applySelectedStyle(); for (int r = 0; r < dataArray.length; r++) { row.createCell(column + r).setCellValue(dataArray[r]); row.getCell(column + r).setCellStyle(style); } //font.setBold(false); }
From source file:com.report.template.LoanCalculator.java
License:Apache License
public static void main(String[] args) throws Exception { Workbook wb;//from w w w . ja v a 2 s . c om if (args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook(); else wb = new XSSFWorkbook(); Map<String, CellStyle> styles = createStyles(wb); Sheet sheet = wb.createSheet("Loan Calculator"); sheet.setPrintGridlines(false); sheet.setDisplayGridlines(false); PrintSetup printSetup = sheet.getPrintSetup(); printSetup.setLandscape(true); sheet.setFitToPage(true); sheet.setHorizontallyCenter(true); sheet.setColumnWidth(0, 3 * 256); sheet.setColumnWidth(1, 3 * 256); sheet.setColumnWidth(2, 11 * 256); sheet.setColumnWidth(3, 14 * 256); sheet.setColumnWidth(4, 14 * 256); sheet.setColumnWidth(5, 14 * 256); sheet.setColumnWidth(6, 14 * 256); createNames(wb); Row titleRow = sheet.createRow(0); titleRow.setHeightInPoints(35); for (int i = 1; i <= 7; i++) { titleRow.createCell(i).setCellStyle(styles.get("title")); } Cell titleCell = titleRow.getCell(2); titleCell.setCellValue("Simple Loan Calculator"); sheet.addMergedRegion(CellRangeAddress.valueOf("$C$1:$H$1")); Row row = sheet.createRow(2); Cell cell = row.createCell(4); cell.setCellValue("Enter values"); cell.setCellStyle(styles.get("item_right")); row = sheet.createRow(3); cell = row.createCell(2); cell.setCellValue("Loan amount"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellValue("123123"); cell.setCellStyle(styles.get("input_$")); cell.setAsActiveCell(); row = sheet.createRow(4); cell = row.createCell(2); cell.setCellValue("Annual interest rate"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellStyle(styles.get("input_%")); row = sheet.createRow(5); cell = row.createCell(2); cell.setCellValue("Loan period in years"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellStyle(styles.get("input_i")); row = sheet.createRow(6); cell = row.createCell(2); cell.setCellValue("Start date of loan"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellStyle(styles.get("input_d")); row = sheet.createRow(8); cell = row.createCell(2); cell.setCellValue("Monthly payment"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellFormula("IF(Values_Entered,Monthly_Payment,\"\")"); cell.setCellStyle(styles.get("formula_$")); row = sheet.createRow(9); cell = row.createCell(2); cell.setCellValue("Number of payments"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellFormula("IF(Values_Entered,Loan_Years*12,\"\")"); cell.setCellStyle(styles.get("formula_i")); row = sheet.createRow(10); cell = row.createCell(2); cell.setCellValue("Total interest"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellFormula("IF(Values_Entered,Total_Cost-Loan_Amount,\"\")"); cell.setCellStyle(styles.get("formula_$")); row = sheet.createRow(11); cell = row.createCell(2); cell.setCellValue("Total cost of loan"); cell.setCellStyle(styles.get("item_left")); cell = row.createCell(4); cell.setCellFormula("IF(Values_Entered,Monthly_Payment*Number_of_Payments,\"\")"); cell.setCellStyle(styles.get("formula_$")); // Write the output to a file String file = "loan-calculator.xls"; if (wb instanceof XSSFWorkbook) file += "x"; FileOutputStream out = new FileOutputStream(file); wb.write(out); out.close(); }
From source file:com.repository2excel.Main.java
License:Apache License
/** * @param args/*w ww. ja va2 s . co m*/ */ @SuppressWarnings("deprecation") public static void main(String[] args) { String xmlRepositoryDefFilePath = ""; /** Read user input */ Scanner scnr = new Scanner(System.in); System.out.println("Enter fully qualified path to customCatalog.xml:"); try { xmlRepositoryDefFilePath = scnr.next(); } catch (InputMismatchException e) { // TODO: } finally { scnr.close(); } RepositoryDefinitionReader reader = new RepositoryDefinitionReader(); System.out.println("Begin reading XML Repository definition file..."); HashSet<Item> items = reader.loadRepositoryDefinition(new File(xmlRepositoryDefFilePath)); System.out.println("Finished reading XML file!"); if (items != null && items.size() > 0) { System.out.println("Preparing to export " + items.size() + " items into Excel Spreadsheet..."); SXSSFWorkbook wb = new SXSSFWorkbook(100); Sheet sh = wb.createSheet(); /** Create cell styles */ CellStyle style = wb.createCellStyle(); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); Iterator<Item> iter = items.iterator(); int rownum = 0; while (iter.hasNext()) { Item item = iter.next(); Row row = sh.createRow(rownum); row.createCell(0, CellType.STRING).setCellValue("Item"); row.createCell(1, CellType.STRING).setCellValue(item.getName()); rownum++; row = sh.createRow(rownum); row.createCell(0, CellType.STRING).setCellValue("Query Cache Size"); row.createCell(1, CellType.STRING).setCellValue(item.getQueryCacheSize()); rownum++; row = sh.createRow(rownum); row.createCell(0, CellType.STRING).setCellValue("Item Cache Size"); row.createCell(1, CellType.STRING).setCellValue(item.getItemCacheSize()); rownum++; HashSet<Property> properties = item.getProperties(); if (properties != null && properties.size() > 0) { Cell cell; row = sh.createRow(rownum); cell = row.createCell(0, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Property"); cell = row.createCell(1, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Type"); cell = row.createCell(2, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Readable"); cell = row.createCell(3, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Writable"); cell = row.createCell(4, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Hidden"); cell = row.createCell(5, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Table"); cell = row.createCell(6, CellType.STRING); cell.setCellStyle(style); cell.setCellValue("Column"); Iterator<Property> pIter = properties.iterator(); while (pIter.hasNext()) { rownum++; row = sh.createRow(rownum); Property property = pIter.next(); /** 0. Name */ cell = row.createCell(0, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.getName()); /** 1. Data Type */ cell = row.createCell(1, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.getDataType()); /** 2. Is Readable */ cell = row.createCell(2, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.isReadable()); /** 3. Is Writable */ cell = row.createCell(3, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.isWriteable()); /** 4. Is Hidden */ cell = row.createCell(4, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.isHidden()); /** 5. Table */ cell = row.createCell(5, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.getTable()); /** 6. Column */ cell = row.createCell(6, CellType.STRING); cell.setCellStyle(style); cell.setCellValue(property.getColumn()); } } rownum++; rownum++; } try { File f = new File("test.xlsx"); FileOutputStream out = new FileOutputStream(f); wb.write(out); out.close(); wb.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // dispose of temporary files backing this workbook on disk wb.dispose(); } } }
From source file:com.rodrigodev.xgen4j_table_generator.test.common.assertion.excel.conditions.ExcelFile.java
License:Open Source License
@Override public boolean matches(InputStream actualInputStream) { boolean result = true; try {//from www . j av a 2s. com try (Workbook expectedWb = WorkbookFactory.create(expectedInputStream)) { Sheet expectedSheet = expectedWb.getSheetAt(0); try (Workbook actualWb = WorkbookFactory.create(actualInputStream)) { Sheet actualSheet = actualWb.getSheetAt(0); int expectedRowCount = expectedSheet.getLastRowNum(); for (int r = 0; r <= expectedRowCount; r++) { Row expectedRow = expectedSheet.getRow(r); Row actualRow = actualSheet.getRow(r); if (actualRow == null) { actualRow = actualSheet.createRow(r); } int expectedCellCount = expectedRow.getLastCellNum(); for (int c = 0; c < expectedCellCount; c++) { Cell expectedCell = expectedRow.getCell(c, Row.CREATE_NULL_AS_BLANK); Cell actualCell = actualRow.getCell(c, Row.CREATE_NULL_AS_BLANK); if (expectedCell.getCellType() == Cell.CELL_TYPE_NUMERIC) { assertThat(actualCell.getNumericCellValue()) .isEqualTo(expectedCell.getNumericCellValue(), offset(0.00001)); } else { expectedCell.setCellType(Cell.CELL_TYPE_STRING); actualCell.setCellType(Cell.CELL_TYPE_STRING); assertThat(actualCell.getStringCellValue()) .isEqualTo(expectedCell.getStringCellValue()); } } } } } } catch (AssertionError error) { describedAs(error.getMessage()); result = false; } catch (Exception e) { throw new RuntimeException(e); } return result; }