List of usage examples for org.apache.poi.ss.usermodel Sheet createRow
Row createRow(int rownum);
From source file:com.photon.phresco.framework.commons.FrameworkUtil.java
License:Apache License
public void addNew(String filePath, String testName, String cellValue[]) throws PhrescoException { try {// ww w .j av a 2s . c o m //FileInputStream myInput = new FileInputStream(filePath); int numCol; int cellno = 0; CellStyle tryStyle[] = new CellStyle[20]; String sheetName = testName; //String cellValue[] = {"","",testName,success, fail,"","","",total,testCoverage,"","",""}; Iterator<Row> rowIterator; File testDir = new File(filePath); StringBuilder sb = new StringBuilder(filePath); if (testDir.isDirectory()) { FilenameFilter filter = new PhrescoFileFilter("", "xlsx"); File[] listFiles = testDir.listFiles(filter); if (listFiles.length != 0) { for (File file1 : listFiles) { if (file1.isFile()) { sb.append(File.separator); sb.append(file1.getName()); break; } } FileInputStream myInput = new FileInputStream(sb.toString()); OPCPackage opc = OPCPackage.open(myInput); XSSFWorkbook myWorkBook = new XSSFWorkbook(opc); XSSFSheet mySheet = myWorkBook.getSheetAt(0); rowIterator = mySheet.rowIterator(); numCol = 13; Row next; for (Cell cell : mySheet.getRow((mySheet.getLastRowNum()) - 2)) { tryStyle[cellno] = cell.getCellStyle(); cellno = cellno + 1; } do { int flag = 0; next = rowIterator.next(); if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index") && ((mySheet.getLastRowNum() - next.getRowNum()) < 3)) { for (Cell cell : next) { cell.setCellType(1); if (cell.getStringCellValue().equalsIgnoreCase("total")) { mySheet.shiftRows((mySheet.getLastRowNum() - 1), (mySheet.getPhysicalNumberOfRows() - 1), 1); flag = 1; } if (flag == 1) break; } if (flag == 1) break; } } while (rowIterator.hasNext()); Row r = null; if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) { r = mySheet.createRow(next.getRowNum() - 1); } else { r = mySheet.createRow(next.getRowNum() + 1); } for (int i = 0; i < numCol; i++) { Cell cell = r.createCell(i); cell.setCellValue(cellValue[i]); // used only when sheet is 'index' if (i == 2) sheetName = cellValue[i]; cell.setCellStyle(tryStyle[i]); } if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) { Sheet fromSheet = myWorkBook.getSheetAt((myWorkBook.getNumberOfSheets() - 1)); Sheet toSheet = myWorkBook.createSheet(sheetName); int i = 0; Iterator<Row> copyFrom = fromSheet.rowIterator(); Row fromRow, toRow; CellStyle newSheetStyle[] = new CellStyle[20]; Integer newSheetType[] = new Integer[100]; String newSheetValue[] = new String[100]; do { fromRow = copyFrom.next(); if (fromRow.getRowNum() == 24) { break; } toRow = toSheet.createRow(i); int numCell = 0; for (Cell cell : fromRow) { Cell newCell = toRow.createCell(numCell); cell.setCellType(1); newSheetStyle[numCell] = cell.getCellStyle(); newCell.setCellStyle(newSheetStyle[numCell]); newSheetType[numCell] = cell.getCellType(); newCell.setCellType(newSheetType[numCell]); if (fromRow.getCell(0).getStringCellValue().length() != 1 && fromRow.getCell(0).getStringCellValue().length() != 2 && fromRow.getCell(0).getStringCellValue().length() != 3) { newSheetValue[numCell] = cell.getStringCellValue(); newCell.setCellValue(newSheetValue[numCell]); } numCell = numCell + 1; } i = i + 1; } while (copyFrom.hasNext()); } // write to file FileOutputStream fileOut = new FileOutputStream(sb.toString()); myWorkBook.write(fileOut); myInput.close(); fileOut.close(); } else { FilenameFilter xlsFilter = new PhrescoFileFilter("", "xls"); File[] xlsListFiles = testDir.listFiles(xlsFilter); if (xlsListFiles.length != 0) { for (File file2 : xlsListFiles) { if (file2.isFile()) { sb.append(File.separator); sb.append(file2.getName()); break; } } FileInputStream myInput = new FileInputStream(sb.toString()); HSSFWorkbook myWorkBook = new HSSFWorkbook(myInput); HSSFSheet mySheet = myWorkBook.getSheetAt(0); rowIterator = mySheet.rowIterator(); numCol = 13; Row next; for (Cell cell : mySheet.getRow((mySheet.getLastRowNum()) - 2)) { tryStyle[cellno] = cell.getCellStyle(); cellno = cellno + 1; } do { int flag = 0; next = rowIterator.next(); if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index") && ((mySheet.getLastRowNum() - next.getRowNum()) < 3)) { for (Cell cell : next) { cell.setCellType(1); if (cell.getStringCellValue().equalsIgnoreCase("total")) { mySheet.shiftRows((mySheet.getLastRowNum() - 1), (mySheet.getPhysicalNumberOfRows() - 1), 1); flag = 1; } if (flag == 1) break; } if (flag == 1) break; } } while (rowIterator.hasNext()); Row r = null; if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) { r = mySheet.createRow(mySheet.getLastRowNum() - 2); } else { r = mySheet.createRow(next.getRowNum() + 1); } for (int i = 0; i < numCol; i++) { Cell cell = r.createCell(i); cell.setCellValue(cellValue[i]); // used only when sheet is 'index' if (i == 2) sheetName = cellValue[i]; cell.setCellStyle(tryStyle[i]); } if ((mySheet.getSheetName().trim()).equalsIgnoreCase("Index")) { Sheet fromSheet = myWorkBook.getSheetAt((myWorkBook.getNumberOfSheets() - 1)); Sheet toSheet = myWorkBook.createSheet(sheetName); int i = 0; Iterator<Row> copyFrom = fromSheet.rowIterator(); Row fromRow, toRow; CellStyle newSheetStyle[] = new CellStyle[20]; Integer newSheetType[] = new Integer[100]; String newSheetValue[] = new String[100]; do { fromRow = copyFrom.next(); if (fromRow.getRowNum() == 24) { break; } toRow = toSheet.createRow(i); int numCell = 0; for (Cell cell : fromRow) { Cell newCell = toRow.createCell(numCell); cell.setCellType(1); newSheetStyle[numCell] = cell.getCellStyle(); newCell.setCellStyle(newSheetStyle[numCell]); newSheetType[numCell] = cell.getCellType(); newCell.setCellType(newSheetType[numCell]); if (fromRow.getCell(0).getStringCellValue().length() != 1 && fromRow.getCell(0).getStringCellValue().length() != 2 && fromRow.getCell(0).getStringCellValue().length() != 3) { newSheetValue[numCell] = cell.getStringCellValue(); newCell.setCellValue(newSheetValue[numCell]); } numCell = numCell + 1; if (numCell == 15) { break; } } i = i + 1; } while (copyFrom.hasNext()); } // write to file FileOutputStream fileOut = new FileOutputStream(sb.toString()); myWorkBook.write(fileOut); myInput.close(); fileOut.close(); } else { FilenameFilter odsFilter = new PhrescoFileFilter("", "ods"); File[] odsListFiles = testDir.listFiles(odsFilter); for (File file1 : odsListFiles) { if (file1.isFile()) { sb.append(File.separator); sb.append(file1.getName()); break; } } File file = new File(sb.toString()); addTestSuiteToOds(file, cellValue); } } } } catch (Exception e) { // throw new PhrescoException(e); } }
From source file:com.plugin.excel.util.ExcelFileHelper.java
License:Apache License
/** * It helps to update cell and format the excell based on the formatting defined in ExcelCell.{@link ExcelFormat} * //from w w w. j a v a 2 s. c o m * @param cell * @param excell * @param style * @param font */ private static void updateCell(Cell cell, ExcelCell excell, Map<IndexedColors, CellStyle> s_cellStyle, Workbook workbook, Font font, Font invisibleFont) { if (excell != null) { // [1] format cell formatCell(workbook, cell, excell, s_cellStyle, font, invisibleFont); // [2] set enum if (!excell.isConsiderEnum()) { if (StringUtils.isNotBlank(excell.getDisplayText())) { cell.setCellValue(excell.getDisplayText()); } if (!excell.isMultiSelect() && excell.isNumberValidation()) { addNumberValidation(cell); } } else { String[] list = (String[]) excell.getRestriction().getEnumValues() .toArray(new String[excell.getRestriction().getEnumValues().size()]); SXSSFSheet sheet = (SXSSFSheet) cell.getSheet(); DataValidationHelper dvHelper = sheet.getDataValidationHelper(); DataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper .createExplicitListConstraint(list); CellRangeAddressList regions = new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); DataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, regions); dataValidation.setSuppressDropDownArrow(true); dataValidation.createErrorBox("Not Applicable", "Can't change the value"); dataValidation.setShowErrorBox(true); try { if (isValidEnumList(list)) { sheet.addValidationData(dataValidation); } else { Sheet hidden = null; String hiddenName = "hidden" + getHiddenIndex(excell.getReferenceText()); Workbook wBook = cell.getSheet().getWorkbook(); if (cell.getSheet().getWorkbook().getSheet(hiddenName) != null) { hidden = wBook.getSheet(hiddenName); } else { hidden = wBook.createSheet(hiddenName); for (int i = 0, length = list.length; i < length; i++) { String name = list[i]; Row row = hidden.createRow(i); Cell cell1 = row.createCell(0); cell1.setCellValue(name); } Name namedCell = hidden.getWorkbook().getName(hiddenName); namedCell = namedCell != null ? namedCell : hidden.getWorkbook().createName(); namedCell.setNameName(hiddenName); namedCell.setRefersToFormula(hiddenName + "!$A$1:$A$" + list.length); } dvConstraint = (XSSFDataValidationConstraint) dvHelper .createFormulaListConstraint(hiddenName); dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, regions); dataValidation.createErrorBox("Not Applicable", "Can't change the value"); dataValidation.setShowErrorBox(true); cell.getSheet().addValidationData(dataValidation); wBook.setSheetHidden(wBook.getSheetIndex(hidden), true); } } catch (Exception e) { String msg = "Excel creation failed while building cell: " + excell.getDisplayText(); throw new IllegalStateException(msg, e); } // cell.setCellValue(excelConfig.getDropDownMsg()); } } }
From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java
public static InputStream convertToGenericTollTagFormat(InputStream is, Long tollCompanyId, GenericDAO genericDAO, ImportMainSheetService importMainSheetService) throws Exception { String tollCompanyName = getTollCompanyName(genericDAO, tollCompanyId); LinkedHashMap<String, String> actualColumnListMap = getTollCompanySpecificMapping(tollCompanyName); List<LinkedList<Object>> tempData = importMainSheetService.importTollCompanySpecificTollTag(is, actualColumnListMap, tollCompanyId); System.out.println("Number of rows = " + tempData.size()); HSSFWorkbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); CellStyle style = wb.createCellStyle(); createColumnHeaders(expectedColumnList, sheet, style); int rowIndex = 1; for (int i = 0; i < tempData.size(); i++) { System.out.println("Creating Row " + i + " with data = \n" + tempData.get(i)); int columnIndex = 0; LinkedList<Object> oneRow = tempData.get(i); Row row = sheet.createRow(rowIndex++); for (Object oneCellValue : oneRow) { if (columnIndex >= expectedColumnList.size()) { // For vendors where more than required columns are read from excel break; }//from w w w . j a va 2s . com System.out.println("Creating Column @ " + columnIndex + " with value = " + oneCellValue); Cell cell = createExcelCell(sheet, row, columnIndex); formatCellValueForTollCompany(wb, cell, oneCellValue, tollCompanyName); columnIndex++; } } InputStream targetStream = createInputStream(wb); return targetStream; }
From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java
private static void createColumnHeaders(LinkedList<String> expectedColumnList, Sheet sheet, CellStyle style) { Row headerRow = sheet.createRow(0); int columnHeaderIndex = 0; for (String columnHeader : expectedColumnList) { // TODO redundant, use actualColumnListMap.keys instead sheet.setColumnWidth(columnHeaderIndex, 256 * 20); Cell cell = headerRow.createCell(columnHeaderIndex++); cell.setCellValue(columnHeader); style.setAlignment(CellStyle.ALIGN_CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(style);/*from w w w.j a v a 2 s.c o m*/ } }
From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java
public static ByteArrayOutputStream createTollUploadSuccessResponse() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFFont font = wb.createFont();/*from ww w.ja va 2 s. com*/ font.setColor(IndexedColors.GREEN.getIndex()); font.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setFont(font); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0); Cell cell = createExcelCell(sheet, row, 0, 256 * 100); cell.setCellStyle(cellStyle); cell.setCellValue("ALL tolls uploaded successfully"); return createOutputStream(wb); }
From source file:com.primovision.lutransport.core.util.TollCompanyTagUploadUtil.java
public static ByteArrayOutputStream createTollUploadExceptionResponse(Exception e) { HSSFWorkbook wb = new HSSFWorkbook(); HSSFFont font = wb.createFont();//from w w w.jav a 2 s . c o m font.setColor(Font.COLOR_RED); font.setBoldweight(Font.BOLDWEIGHT_BOLD); CellStyle cellStyle = wb.createCellStyle(); cellStyle.setFont(font); Sheet sheet = wb.createSheet(); Row row = sheet.createRow(0); Cell cell = createExcelCell(sheet, row, 0, 256 * 100); cell.setCellStyle(cellStyle); cell.setCellValue("An error occurred while uploading!!!"); return createOutputStream(wb); }
From source file:com.qihang.winter.poi.excel.export.base.ExcelExportBase.java
License:Apache License
/** * ? Cells/*www .j a va 2s.c o m*/ * * @param styles * @param rowHeight * @throws Exception */ public int createCells(Drawing patriarch, int index, Object t, List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook, short rowHeight) throws Exception { com.qihang.winter.poi.excel.entity.params.ExcelExportEntity entity; Row row = sheet.createRow(index); row.setHeight(rowHeight); int maxHeight = 1, cellNum = 0; int indexKey = createIndexCell(row, 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 = getListCellValue(entity, t); int listC = 0; for (Object obj : list) { createListCells(patriarch, index + listC, cellNum, obj, entity.getList(), sheet, workbook); 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(false, entity) : getStyles(true, entity), 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()) { for (int i = index + 1; i < index + maxHeight; i++) { sheet.getRow(i).createCell(cellNum); sheet.getRow(i).getCell(cellNum).setCellStyle(getStyles(false, entity)); } sheet.addMergedRegion(new CellRangeAddress(index, index + maxHeight - 1, cellNum, cellNum)); cellNum++; } } return maxHeight; }
From source file:com.qihang.winter.poi.excel.export.base.ExcelExportBase.java
License:Apache License
/** * List??Cells//from w w w . ja v a2 s . c om * * @param styles */ public void createListCells(Drawing patriarch, int index, int cellNum, Object obj, List<com.qihang.winter.poi.excel.entity.params.ExcelExportEntity> excelParams, Sheet sheet, Workbook workbook) throws Exception { com.qihang.winter.poi.excel.entity.params.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(false, entity) : getStyles(true, entity), entity); } else { createImageCell(patriarch, entity, row, cellNum++, value == null ? "" : value.toString(), obj); } } }
From source file:com.qualogy.qafe.service.DocumentExporter.java
License:Apache License
public static void exportExcel(DocumentExportInput input, ByteArrayOutputStream bout) { Workbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet("Exported data"); if (input.getData() != null) { if (bout != null) { short index = 0; List<String> headerColumns = input.getColumnSequence(); if (headerColumns == null) { headerColumns = getHeaderColumns(input.getData()); }/*from ww w .j a v a2s. c o m*/ if (headerColumns != null) { if (input.isGenerateColumnHeader()) { Row row = sheet.createRow(index++); for (int i = 0; i < headerColumns.size(); i++) { String columnHeader = headerColumns.get(i); Cell cell = row.createCell(i); cell.setCellValue(columnHeader); } } for (Map<String, Object> map : input.getData()) { Row row = sheet.createRow(index++); for (int i = 0; i < headerColumns.size(); i++) { String key = headerColumns.get(i); Object value = map.get(key); Cell cell = row.createCell(i); setCellValue(cell, value); } } } } } try { wb.write(bout); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.quanticate.opensource.datalistdownload.DataListDownloadWebScript.java
License:Open Source License
@Override protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties) throws IOException { NodeRef list = (NodeRef) resource;// ww w . j a v a 2 s . c om List<NodeRef> items = getItems(list); // Our various formats DataFormat formatter = workbook.createDataFormat(); CellStyle styleInt = workbook.createCellStyle(); styleInt.setDataFormat(formatter.getFormat("0")); CellStyle styleDate = workbook.createCellStyle(); styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd")); CellStyle styleDouble = workbook.createCellStyle(); styleDouble.setDataFormat(formatter.getFormat("General")); CellStyle styleNewLines = workbook.createCellStyle(); styleNewLines.setWrapText(true); // Export the items int rowNum = 1, colNum = 0; for (NodeRef item : items) { Row r = sheet.createRow(rowNum); colNum = 0; for (QName prop : properties) { Cell c = r.createCell(colNum); Pair<Object, String> valAndLink = identifyValueAndLink(item, prop); if (valAndLink == null) { // This property isn't set c.setCellType(Cell.CELL_TYPE_BLANK); } else { Object val = valAndLink.getFirst(); // Multi-line property? if (val instanceof String[]) { String[] lines = (String[]) val; StringBuffer text = new StringBuffer(); for (String line : lines) { if (text.length() > 0) { text.append('\n'); } text.append(line); } String v = text.toString(); c.setCellValue(v); if (lines.length > 1) { c.setCellStyle(styleNewLines); r.setHeightInPoints(lines.length * sheet.getDefaultRowHeightInPoints()); } } // Regular properties else if (val instanceof String) { c.setCellValue((String) val); } else if (val instanceof Date) { c.setCellValue((Date) val); c.setCellStyle(styleDate); } else if (val instanceof Integer || val instanceof Long) { double v = 0.0; if (val instanceof Long) v = (double) (Long) val; if (val instanceof Integer) v = (double) (Integer) val; c.setCellValue(v); c.setCellStyle(styleInt); } else if (val instanceof Float || val instanceof Double) { double v = 0.0; if (val instanceof Float) v = (double) (Float) val; if (val instanceof Double) v = (double) (Double) val; c.setCellValue(v); c.setCellStyle(styleDouble); } else { // TODO System.err .println("TODO: Handle Excel output of " + val.getClass().getName() + " - " + val); } } colNum++; } rowNum++; } // Sensible column widths please! colNum = 0; for (QName prop : properties) { sheet.autoSizeColumn(colNum); colNum++; } }