List of usage examples for org.apache.poi.ss.usermodel Cell setCellComment
void setCellComment(Comment comment);
From source file:com.quanticate.opensource.datalistdownload.DeclarativeSpreadsheetWebScript.java
License:Open Source License
/** * Generates the spreadsheet, based on the properties in the header * and a callback for the body.//from w w w .j av a 2 s. co m */ public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status, Map<String, Object> model) throws IOException { Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)"); // Build up the details of the header List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req); String[] headings = new String[propertyDetails.size()]; String[] descriptions = new String[propertyDetails.size()]; boolean[] required = new boolean[propertyDetails.size()]; for (int i = 0; i < headings.length; i++) { Pair<QName, Boolean> property = propertyDetails.get(i); if (property == null || property.getFirst() == null) { headings[i] = ""; required[i] = false; } else { QName column = property.getFirst(); required[i] = property.getSecond(); // Ask the dictionary service nicely for the details PropertyDefinition pd = dictionaryService.getProperty(column); if (pd != null && pd.getTitle(dictionaryService) != null) { // Use the friendly titles, which may even be localised! headings[i] = pd.getTitle(dictionaryService); descriptions[i] = pd.getDescription(dictionaryService); } else { // Nothing friendly found, try to munge the raw qname into // something we can show to a user... String raw = column.getLocalName(); raw = raw.substring(0, 1).toUpperCase() + raw.substring(1); Matcher m = qnameMunger.matcher(raw); if (m.matches()) { headings[i] = m.group(1) + " " + m.group(2); } else { headings[i] = raw; } } } } // Build a list of just the properties List<QName> properties = new ArrayList<QName>(propertyDetails.size()); for (Pair<QName, Boolean> p : propertyDetails) { QName qn = null; if (p != null) { qn = p.getFirst(); } properties.add(qn); } // Output if ("csv".equals(format)) { StringWriter sw = new StringWriter(); CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY); csv.println(headings); populateBody(resource, csv, properties); model.put(MODEL_CSV, sw.toString()); } else if ("odf".equals(format) || "ods".equals(format)) { try { SpreadsheetDocument odf = SpreadsheetDocument.newSpreadsheetDocument(); // Add the header row Table sheet = odf.appendSheet("Export"); org.odftoolkit.simple.table.Row hr = sheet.appendRow(); // TODO // Have the contents populated // TODO // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); odf.save(baos); model.put(MODEL_ODF, baos.toByteArray()); } catch (Exception e) { throw new WebScriptException("Error creating ODF file", e); } } else { Workbook wb; if ("xlsx".equals(format)) { wb = new XSSFWorkbook(); // TODO Properties } else { wb = new HSSFWorkbook(); // TODO Properties } // Add our header row Sheet sheet = wb.createSheet("Export"); Row hr = sheet.createRow(0); sheet.createFreezePane(0, 1); Font fb = wb.createFont(); fb.setBoldweight(Font.BOLDWEIGHT_BOLD); Font fi = wb.createFont(); fi.setBoldweight(Font.BOLDWEIGHT_BOLD); fi.setItalic(true); CellStyle csReq = wb.createCellStyle(); csReq.setFont(fb); CellStyle csOpt = wb.createCellStyle(); csOpt.setFont(fi); // Populate the header Drawing draw = null; for (int i = 0; i < headings.length; i++) { Cell c = hr.createCell(i); c.setCellValue(headings[i]); if (required[i]) { c.setCellStyle(csReq); } else { c.setCellStyle(csOpt); } if (headings[i].length() == 0) { sheet.setColumnWidth(i, 3 * 250); } else { sheet.setColumnWidth(i, 18 * 250); } if (descriptions[i] != null && descriptions[i].length() > 0) { // Add a description for it too if (draw == null) { draw = sheet.createDrawingPatriarch(); } ClientAnchor ca = wb.getCreationHelper().createClientAnchor(); ca.setCol1(c.getColumnIndex()); ca.setCol2(c.getColumnIndex() + 1); ca.setRow1(hr.getRowNum()); ca.setRow2(hr.getRowNum() + 2); Comment cmt = draw.createCellComment(ca); cmt.setAuthor(""); cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i])); cmt.setVisible(false); c.setCellComment(cmt); } } // Have the contents populated populateBody(resource, wb, sheet, properties); // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); model.put(MODEL_EXCEL, baos.toByteArray()); } }
From source file:com.runwaysdk.dataaccess.io.ExcelExportSheet.java
License:Open Source License
protected void writeHeader(Sheet sheet, Drawing drawing, Row nameRow, Row labelRow, int i, ExcelColumn column, CellStyle boldStyle) {/* www .j av a 2 s . c o m*/ CreationHelper helper = sheet.getWorkbook().getCreationHelper(); // Notify the listeners for (ExcelExportListener listener : listeners) { listener.preHeader(column); } nameRow.createCell(i).setCellValue(helper.createRichTextString(column.getAttributeName())); Cell cell = labelRow.createCell(i); cell.setCellValue(helper.createRichTextString(column.getDisplayLabel())); if (column.isRequired() && boldStyle != null) { cell.setCellStyle(boldStyle); } if (column.getDescription() != null && column.getDescription().length() > 0) { ClientAnchor anchor = helper.createClientAnchor(); anchor.setDx1(0); anchor.setDy1(0); anchor.setDx2(0); anchor.setDy2(0); anchor.setCol1(0); anchor.setRow1(0); anchor.setCol2(0); anchor.setRow2(4); Comment comment = drawing.createCellComment(anchor); comment.setString(helper.createRichTextString(column.getDescription())); cell.setCellComment(comment); } sheet.autoSizeColumn((short) i); }
From source file:com.vaadin.addon.spreadsheet.action.InsertDeleteCellCommentAction.java
License:Open Source License
private void createCellComment(Spreadsheet spreadsheet, Sheet sheet, Cell cell, CellReference cellRef) { CreationHelper factory = sheet.getWorkbook().getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); anchor.setCol1(cell.getColumnIndex()); anchor.setCol2(cell.getColumnIndex() + 1); anchor.setRow1(cell.getRowIndex());// ww w . ja va 2 s . co m anchor.setRow2(cell.getRowIndex() + 3); // Create the comment and set the text+author Comment comment = drawing.createCellComment(anchor); RichTextString str = factory.createRichTextString(""); comment.setString(str); // Fetch author from provider or fall back to default String author = null; if (spreadsheet.getCommentAuthorProvider() != null) { author = spreadsheet.getCommentAuthorProvider().getAuthorForComment(cellRef); } if (author == null || author.trim().isEmpty()) { author = "Spreadsheet User"; } comment.setAuthor(author); // Assign the comment to the cell cell.setCellComment(comment); }
From source file:de.enerko.reports2.engine.Report.java
License:Apache License
/** * This method adds a new cell to the sheet of a workbook. It could * (together with {@link #fill(Workbook, Cell, String, String, boolean)}) be moved to * the {@link CellDefinition} itself, but that would mean that the {@link CellDefinition} is * tied to a specific Excel API. Having those methods here allows the Report to become * an interface if a second engine (i.e. JXL) should be added in the future. * @param workbook//from w w w . ja v a 2s. com * @param sheet * @param cellDefinition */ private void addCell(final Workbook workbook, final Sheet sheet, final CellDefinition cellDefinition) { final int columnNum = cellDefinition.column, rowNum = cellDefinition.row; Row row = sheet.getRow(rowNum); if (row == null) row = sheet.createRow(rowNum); Cell cell = row.getCell(columnNum); // If the cell already exists and is no blank cell // it will be used including all formating if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) { cell = fill(workbook, cell, cellDefinition, false); } // Otherwise a new cell will be created, the datatype set and // optionally a format will be created else { cell = fill(workbook, row.createCell(columnNum), cellDefinition, true); final Sheet referenceSheet; if (cellDefinition.getReferenceCell() != null && (referenceSheet = workbook.getSheet(cellDefinition.getReferenceCell().sheetname)) != null) { final Row referenceRow = referenceSheet.getRow(cellDefinition.getReferenceCell().row); final Cell referenceCell = referenceRow == null ? null : referenceRow.getCell(cellDefinition.getReferenceCell().column); if (referenceCell != null && referenceCell.getCellStyle() != null) cell.setCellStyle(referenceCell.getCellStyle()); } } // Add an optional comment if (cellDefinition.hasComment()) { final CreationHelper factory = workbook.getCreationHelper(); final Drawing drawing = sheet.createDrawingPatriarch(); final ClientAnchor commentAnchor = factory.createClientAnchor(); final int col1 = cellDefinition.comment.column == null ? cell.getColumnIndex() + 1 : cellDefinition.comment.column; final int row1 = cellDefinition.comment.row == null ? cell.getRowIndex() : cellDefinition.comment.row; commentAnchor.setCol1(col1); commentAnchor.setRow1(row1); commentAnchor.setCol2(col1 + Math.max(1, cellDefinition.comment.width)); commentAnchor.setRow2(row1 + Math.max(1, cellDefinition.comment.height)); final Comment comment = drawing.createCellComment(commentAnchor); comment.setString(factory.createRichTextString(cellDefinition.comment.text)); comment.setAuthor(cellDefinition.comment.author); comment.setVisible(cellDefinition.comment.visible); cell.setCellComment(comment); } }
From source file:de.fme.alfresco.repo.web.scripts.DeclarativeSpreadsheetWebScript.java
License:Open Source License
/** * Generates the spreadsheet, based on the properties in the header * and a callback for the body./*from w w w .j a va 2 s. c o m*/ */ public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status, Map<String, Object> model) throws IOException { Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)"); // Build up the details of the header List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req); String[] headings = new String[propertyDetails.size()]; String[] descriptions = new String[propertyDetails.size()]; boolean[] required = new boolean[propertyDetails.size()]; for (int i = 0; i < headings.length; i++) { Pair<QName, Boolean> property = propertyDetails.get(i); if (property == null || property.getFirst() == null) { headings[i] = ""; required[i] = false; } else { QName column = property.getFirst(); required[i] = property.getSecond(); // Ask the dictionary service nicely for the details PropertyDefinition pd = dictionaryService.getProperty(column); if (pd != null && pd.getTitle() != null) { // Use the friendly titles, which may even be localised! headings[i] = pd.getTitle(); descriptions[i] = pd.getDescription(); } else { // Nothing friendly found, try to munge the raw qname into // something we can show to a user... String raw = column.getLocalName(); raw = raw.substring(0, 1).toUpperCase() + raw.substring(1); Matcher m = qnameMunger.matcher(raw); if (m.matches()) { headings[i] = m.group(1) + " " + m.group(2); } else { headings[i] = raw; } } } } // Build a list of just the properties List<QName> properties = new ArrayList<QName>(propertyDetails.size()); for (Pair<QName, Boolean> p : propertyDetails) { QName qn = null; if (p != null) { qn = p.getFirst(); } properties.add(qn); } // Output if ("csv".equals(format)) { StringWriter sw = new StringWriter(); CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY); csv.println(headings); populateBody(resource, csv, properties); model.put(MODEL_CSV, sw.toString()); } else { Workbook wb; if ("xlsx".equals(format)) { wb = new XSSFWorkbook(); // TODO Properties } else { wb = new HSSFWorkbook(); // TODO Properties } // Add our header row Sheet sheet = wb.createSheet("Export"); Row hr = sheet.createRow(0); try { sheet.createFreezePane(0, 1); } catch (IndexOutOfBoundsException e) { //https://issues.apache.org/bugzilla/show_bug.cgi?id=51431 & http://stackoverflow.com/questions/6469693/apache-poi-clearing-freeze-split-panes } Font fb = wb.createFont(); fb.setBoldweight(Font.BOLDWEIGHT_BOLD); Font fi = wb.createFont(); fi.setBoldweight(Font.BOLDWEIGHT_BOLD); fi.setItalic(true); CellStyle csReq = wb.createCellStyle(); csReq.setFont(fb); CellStyle csOpt = wb.createCellStyle(); csOpt.setFont(fi); // Populate the header Drawing draw = null; for (int i = 0; i < headings.length; i++) { Cell c = hr.createCell(i); c.setCellValue(headings[i]); if (required[i]) { c.setCellStyle(csReq); } else { c.setCellStyle(csOpt); } if (headings[i].length() == 0) { sheet.setColumnWidth(i, 3 * 250); } else { sheet.setColumnWidth(i, 18 * 250); } if (descriptions[i] != null && descriptions[i].length() > 0) { // Add a description for it too if (draw == null) { draw = sheet.createDrawingPatriarch(); } ClientAnchor ca = wb.getCreationHelper().createClientAnchor(); ca.setCol1(c.getColumnIndex()); ca.setCol2(c.getColumnIndex() + 1); ca.setRow1(hr.getRowNum()); ca.setRow2(hr.getRowNum() + 2); Comment cmt = draw.createCellComment(ca); cmt.setAuthor(""); cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i])); cmt.setVisible(false); c.setCellComment(cmt); } } // Have the contents populated populateBody(resource, wb, sheet, properties); // Save it for the template ByteArrayOutputStream baos = new ByteArrayOutputStream(); wb.write(baos); model.put(MODEL_EXCEL, baos.toByteArray()); } }
From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java
License:Open Source License
/** * Adds headers stored in <code>headers</code> to the current sheet. If required, a special width * for the corresponding column can be set by providing a value in <code>headersWidth</code> using * header as key.<br/>//from w w w.j av a2s .co m * <b>IMPORTANT</b>: Headers are added in the order provided in <code>headers</code>. * * @param headers * headers to be added */ public void addHeaders(int sheetId, List<ExcelSheet.Header> headers) { Sheet sheet = getSheetById(sheetId); Drawing drawing = sheet.createDrawingPatriarch(); CreationHelper factory = sheet.getWorkbook().getCreationHelper(); Row row = sheet.createRow(this.getCurrentRowOfSheet(sheet, 3)); int columnIndex = 0; for (ExcelSheet.Header header : headers) { int currColumnIndex = columnIndex; Cell cell = row.createCell(columnIndex); if (header.getDescription() != null) { ClientAnchor commentAnchor = factory.createClientAnchor(); //Sizing the comment 1x3 cells commentAnchor.setCol1(cell.getColumnIndex()); commentAnchor.setCol2(cell.getColumnIndex() + 1); commentAnchor.setRow1(row.getRowNum()); commentAnchor.setRow2(row.getRowNum() + 3); Comment comment = drawing.createCellComment(commentAnchor); RichTextString str = factory.createRichTextString(header.getDescription()); comment.setString(str); comment.setAuthor(""); cell.setCellComment(comment); } setCellValue(cell, header.getLabel(), getHeaderTableStyle()); Integer width = header.getWidth(); if (width != null) { sheet.setColumnWidth(currColumnIndex, width.intValue()); } columnIndex++; } LOGGER.debug("Added headers."); }
From source file:de.jlo.talendcomp.excel.SpreadsheetOutput.java
License:Apache License
private void setCellComment(Cell cell, String comment) { if (comment == null || comment.trim().isEmpty()) { cell.removeCellComment();//from w ww . j av a 2 s. com } else { Comment c = cell.getCellComment(); if (c == null) { ClientAnchor anchor = creationHelper.createClientAnchor(); anchor.setRow1(cell.getRowIndex()); anchor.setRow2(cell.getRowIndex() + commentHeight); anchor.setCol1(cell.getColumnIndex() + 1); anchor.setCol2(cell.getColumnIndex() + commentWidth + 1); anchor.setAnchorType(AnchorType.MOVE_AND_RESIZE); c = getDrawing().createCellComment(anchor); c.setVisible(false); if (commentAuthor != null) { c.setAuthor(commentAuthor); } cell.setCellComment(c); } RichTextString rts = creationHelper.createRichTextString(comment); c.setString(rts); } }
From source file:excel.CellComments.java
License:Apache License
public static void main(String[] args) throws IOException { try (Workbook wb = new XSSFWorkbook()) { CreationHelper factory = wb.getCreationHelper(); Sheet sheet = wb.createSheet();/*from w ww. ja v a2s.co m*/ Cell cell1 = sheet.createRow(3).createCell(5); cell1.setCellValue("F4"); Drawing<?> drawing = sheet.createDrawingPatriarch(); ClientAnchor anchor = factory.createClientAnchor(); Comment comment1 = drawing.createCellComment(anchor); RichTextString str1 = factory.createRichTextString("Hello, World!"); comment1.setString(str1); comment1.setAuthor("Apache POI"); cell1.setCellComment(comment1); Cell cell2 = sheet.createRow(2).createCell(2); cell2.setCellValue("C3"); Comment comment2 = drawing.createCellComment(anchor); RichTextString str2 = factory.createRichTextString("XSSF can set cell comments"); //apply custom font to the text in the comment Font font = wb.createFont(); font.setFontName("Arial"); font.setFontHeightInPoints((short) 14); font.setBold(true); font.setColor(IndexedColors.RED.getIndex()); str2.applyFont(font); comment2.setString(str2); comment2.setAuthor("Apache POI"); comment2.setAddress(new CellAddress("C3")); try (FileOutputStream out = new FileOutputStream("comments.xlsx")) { wb.write(out); } } }
From source file:gov.nih.nci.evs.app.neopl.XLStoXLSX.java
License:Open Source License
/** * @param args// www . j a v a 2 s .c o m * @throws InvalidFormatException * @throws IOException */ public static void run(String inputfile, String outputfile) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(inputfile)); try { Workbook wbIn = new HSSFWorkbook(in); File outFn = new File(outputfile); if (outFn.exists()) { outFn.delete(); } Workbook wbOut = new XSSFWorkbook(); int sheetCnt = wbIn.getNumberOfSheets(); for (int i = 0; i < sheetCnt; i++) { Sheet sIn = wbIn.getSheetAt(0); Sheet sOut = wbOut.createSheet(sIn.getSheetName()); Iterator<Row> rowIt = sIn.rowIterator(); while (rowIt.hasNext()) { Row rowIn = rowIt.next(); Row rowOut = sOut.createRow(rowIn.getRowNum()); Iterator<Cell> cellIt = rowIn.cellIterator(); while (cellIt.hasNext()) { Cell cellIn = cellIt.next(); Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType()); switch (cellIn.getCellType()) { case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_BOOLEAN: cellOut.setCellValue(cellIn.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: cellOut.setCellValue(cellIn.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: cellOut.setCellFormula(cellIn.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: cellOut.setCellValue(cellIn.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: cellOut.setCellValue(cellIn.getStringCellValue()); break; } { CellStyle styleIn = cellIn.getCellStyle(); CellStyle styleOut = cellOut.getCellStyle(); styleOut.setDataFormat(styleIn.getDataFormat()); } cellOut.setCellComment(cellIn.getCellComment()); // HSSFCellStyle cannot be cast to XSSFCellStyle // cellOut.setCellStyle(cellIn.getCellStyle()); } } } OutputStream out = new BufferedOutputStream(new FileOutputStream(outFn)); try { wbOut.write(out); } finally { out.close(); } } finally { in.close(); } }
From source file:invoiceapplication.CopyRowOriginal.java
public static void copyRow(Sheet worksheet, int sourceRowNum, int destRowNum) { // Get the source / new row Row newRow = worksheet.getRow(destRowNum); Row sourceRow = worksheet.getRow(sourceRowNum); // If the row exists in destination, push down all rows by 1 else create a new row if (newRow != null) { worksheet.shiftRows(newRow.getRowNum(), worksheet.getLastRowNum(), 1, true, true); } else {/* ww w . ja v a 2 s . c o m*/ newRow = worksheet.createRow(destRowNum); } copyAnyMergedRegions(worksheet, sourceRow, newRow); // Loops through source column to add to new row for (int i = 0; i < sourceRow.getLastCellNum(); i++) { //Grab a copy of the old/new cell Cell oldCell = sourceRow.getCell(i); Cell newCell = newRow.createCell(i); // if the old cell is null jump to next cell if (oldCell == null) { newCell = null; continue; } // Use old cell style newCell.setCellStyle(oldCell.getCellStyle()); // If there is a cell comment, copy if (newCell.getCellComment() != null) { newCell.setCellComment(oldCell.getCellComment()); } // If there is a cell hyperlink, copy if (oldCell.getHyperlink() != null) { newCell.setHyperlink(oldCell.getHyperlink()); } // Set the cell data type newCell.setCellType(oldCell.getCellType()); // Set the cell data value switch (oldCell.getCellType()) { case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: newCell.setCellValue(oldCell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getStringCellValue()); break; } } }