List of usage examples for org.apache.poi.ss.usermodel Sheet createRow
Row createRow(int rownum);
From source file:bad.robot.excel.matchers.StubCell.java
License:Apache License
private static Cell create(int row, int column, int type) { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(); Cell cell = sheet.createRow(row).createCell(column, type); return cell;/* w w w .ja v a2 s . c om*/ }
From source file:bad.robot.excel.row.CopyRow.java
License:Apache License
/** * Copies a row from a row index on the given workbook and sheet to another row index. If the destination row is * already occupied, shift all rows down to make room. * */// ww w. j a va 2 s . com public static void copyRow(Workbook workbook, Sheet worksheet, RowIndex from, RowIndex to) { Row sourceRow = worksheet.getRow(from.value()); Row newRow = worksheet.getRow(to.value()); if (alreadyExists(newRow)) worksheet.shiftRows(to.value(), worksheet.getLastRowNum(), 1); else newRow = worksheet.createRow(to.value()); for (int i = 0; i < sourceRow.getLastCellNum(); i++) { Cell oldCell = sourceRow.getCell(i); Cell newCell = newRow.createCell(i); if (oldCell != null) { copyCellStyle(workbook, oldCell, newCell); copyCellComment(oldCell, newCell); copyCellHyperlink(oldCell, newCell); copyCellDataTypeAndValue(oldCell, newCell); } } copyAnyMergedRegions(worksheet, sourceRow, newRow); }
From source file:bad.robot.excel.row.Row.java
License:Apache License
public void insertAt(Workbook workbook, SheetIndex sheetIndex, RowIndex rowIndex) { Sheet sheet = workbook.getSheetAt(sheetIndex.value()); sheet.shiftRows(rowIndex.value(), sheet.getLastRowNum(), shiftDownAmount); org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowIndex.value()); copyCellsTo(row, workbook);//from ww w .ja v a 2 s . c o m }
From source file:bad.robot.excel.row.Row.java
License:Apache License
private static org.apache.poi.ss.usermodel.Row createRow(Sheet sheet) { if (sheet.getPhysicalNumberOfRows() == 0) return sheet.createRow(0); return sheet.createRow(sheet.getLastRowNum() + 1); }
From source file:bad.robot.excel.workbook.NavigablePoiWorkbook.java
License:Apache License
private org.apache.poi.ss.usermodel.Row getRowForCoordinate(RowIndex rowIndex, SheetIndex sheetIndex) { Sheet sheet = poi.getSheetAt(sheetIndex.value()); org.apache.poi.ss.usermodel.Row row = sheet.getRow(rowIndex.value()); if (row == null) row = sheet.createRow(rowIndex.value()); return row;/* w w w .ja va2 s .c o m*/ }
From source file:bad.robot.excel.workbook.PoiWorkbook.java
License:Apache License
private org.apache.poi.ss.usermodel.Row getRowForCoordinate(Coordinate coordinate) { Sheet sheet = workbook.getSheetAt(coordinate.getSheet().value()); org.apache.poi.ss.usermodel.Row row = sheet.getRow(coordinate.getRow().value()); if (row == null) row = sheet.createRow(coordinate.getRow().value()); return row;// w ww . ja v a 2s . c om }
From source file:balony.tableWriter.java
public static void writeTable(JFrame parent, Object[][] tableData, String[] colNames) { String opts[] = { "Tab-delimited text (raw)", "Excel .xls", "Excel 2007+ .xlsx" }; int i = JOptionPane.showOptionDialog(parent, "Choose output format:", "Export Table", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, opts, opts[0]); if (i == JOptionPane.CLOSED_OPTION) { return;/*from ww w. ja v a 2s. c o m*/ } String[] chars = { ":", "[", "]", "/", "\\", "?", "*" }; String fname = parent.getTitle(); for (String c : chars) { fname = fname.replace(c, ""); } JFileChooser jfc = new JFileChooser(); if (i == 0) { jfc.setFileFilter(new FileNameExtensionFilter("Tab-delimited text files", "txt")); jfc.setSelectedFile(new File(fname.concat(".txt"))); } if (i == 1) { jfc.setFileFilter(new FileNameExtensionFilter("Excel .xls files", "xls")); jfc.setSelectedFile(new File(fname.concat(".xls"))); } if (i == 2) { jfc.setFileFilter(new FileNameExtensionFilter("Excel .xlsx files", "xlsx")); jfc.setSelectedFile(new File(fname.concat(".xlsx"))); } int rv = jfc.showSaveDialog(parent); if (rv == JFileChooser.APPROVE_OPTION) { File f = jfc.getSelectedFile(); try { if (i == 0) { BufferedWriter out = new BufferedWriter(new FileWriter(f)); for (String columnName : colNames) { out.write(columnName); out.write("\t"); } out.newLine(); for (Object[] tableData1 : tableData) { for (int k = 0; k < colNames.length; k++) { if (tableData1[k] != null) { out.write(tableData1[k].toString()); } out.write("\t"); } out.newLine(); } out.close(); } if (i > 0) { Workbook wb; if (i == 1) { wb = new HSSFWorkbook(); } else { wb = new XSSFWorkbook(); } Sheet sheet = wb.createSheet(fname); Row r; CellStyle style; sheet.createFreezePane(0, 1); for (int j = 0; j < tableData.length; j++) { r = sheet.createRow(j + 1); for (int k = 0; k < colNames.length; k++) { if (tableData[j][k] != null) { Cell c = r.createCell(k); if (tableData[j][k] instanceof Integer) { c.setCellType(Cell.CELL_TYPE_NUMERIC); int v = ((Integer) tableData[j][k]); c.setCellValue(v); } else { if (tableData[j][k] instanceof Double) { c.setCellType(Cell.CELL_TYPE_NUMERIC); double v = ((Double) tableData[j][k]); c.setCellValue(v); } else { c.setCellType(Cell.CELL_TYPE_STRING); c.setCellValue(tableData[j][k].toString()); } } } } } r = sheet.createRow(0); style = wb.createCellStyle(); Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); for (int k = 0; k < colNames.length; k++) { Cell c = r.createCell(k); c.setCellType(Cell.CELL_TYPE_STRING); c.setCellStyle(style); c.setCellValue(colNames[k]); } FileOutputStream fos = new FileOutputStream(f); wb.write(fos); fos.close(); } } catch (Exception ex) { Logger.getLogger(dataTable.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(parent, "File error: ".concat(ex.getLocalizedMessage()), "File Error", JOptionPane.ERROR_MESSAGE); return; } int n = JOptionPane.showOptionDialog(parent, "File saved. Open in default application?", "Message", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (n == JOptionPane.YES_OPTION) { try { Desktop d = Desktop.getDesktop(); d.open(f); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } } } }
From source file:bandaru_excelreadwrite.WritetoExcel.java
public void writeSongsListToExcel(List<Song> songList) { /*//from w ww . ja va 2 s. c o m Use XSSF for xlsx format and for xls use HSSF */ Workbook workbook = new XSSFWorkbook(); /* create new sheet */ Sheet songsSheet = workbook.createSheet("Albums"); XSSFCellStyle my_style = (XSSFCellStyle) workbook.createCellStyle(); /* Create XSSFFont object from the workbook */ XSSFFont my_font = (XSSFFont) workbook.createFont(); /* setting cell color */ CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); /* setting Header color */ CellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(IndexedColors.DARK_RED.getIndex()); style2.setFillPattern(CellStyle.SOLID_FOREGROUND); style2.setAlignment(style2.ALIGN_CENTER); Row rowName = songsSheet.createRow(1); /* Merging the cells */ songsSheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3)); /* Applying style to attribute name */ int nameCellIndex = 1; Cell namecell = rowName.createCell(nameCellIndex++); namecell.setCellValue("Name"); namecell.setCellStyle(style); Cell cel = rowName.createCell(nameCellIndex++); cel.setCellValue("Bandaru, Sreekanth"); /* Applying underline to Name */ my_font.setUnderline(XSSFFont.U_SINGLE); my_style.setFont(my_font); /* Attaching the style to the cell */ CellStyle combined = workbook.createCellStyle(); combined.cloneStyleFrom(my_style); combined.cloneStyleFrom(style); combined.setAlignment(combined.ALIGN_CENTER); cel.setCellStyle(combined); /* Applying colors to header */ Row rowMain = songsSheet.createRow(3); SheetConditionalFormatting sheetCF = songsSheet.getSheetConditionalFormatting(); ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("3"); PatternFormatting fill1 = rule1.createPatternFormatting(); fill1.setFillBackgroundColor(IndexedColors.LIME.index); fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND); CellRangeAddress[] regions = { CellRangeAddress.valueOf("A4:F4") }; sheetCF.addConditionalFormatting(regions, rule1); /* setting new rule to apply alternate colors to cells having same Genre */ ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule("4"); PatternFormatting fill2 = rule2.createPatternFormatting(); fill2.setFillBackgroundColor(IndexedColors.LEMON_CHIFFON.index); fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND); CellRangeAddress[] regionsAction = { CellRangeAddress.valueOf("A5:F5"), CellRangeAddress.valueOf("A6:F6"), CellRangeAddress.valueOf("A7:F7"), CellRangeAddress.valueOf("A8:F8"), CellRangeAddress.valueOf("A13:F13"), CellRangeAddress.valueOf("A14:F14"), CellRangeAddress.valueOf("A15:F15"), CellRangeAddress.valueOf("A16:F16"), CellRangeAddress.valueOf("A23:F23"), CellRangeAddress.valueOf("A24:F24"), CellRangeAddress.valueOf("A25:F25"), CellRangeAddress.valueOf("A26:F26") }; /* setting new rule to apply alternate colors to cells having same Fenre */ ConditionalFormattingRule rule3 = sheetCF.createConditionalFormattingRule("4"); PatternFormatting fill3 = rule3.createPatternFormatting(); fill3.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index); fill3.setFillPattern(PatternFormatting.SOLID_FOREGROUND); CellRangeAddress[] regionsAdv = { CellRangeAddress.valueOf("A9:F9"), CellRangeAddress.valueOf("A10:F10"), CellRangeAddress.valueOf("A11:F11"), CellRangeAddress.valueOf("A12:F12"), CellRangeAddress.valueOf("A17:F17"), CellRangeAddress.valueOf("A18:F18"), CellRangeAddress.valueOf("A19:F19"), CellRangeAddress.valueOf("A20:F20"), CellRangeAddress.valueOf("A21:F21"), CellRangeAddress.valueOf("A22:F22"), CellRangeAddress.valueOf("A27:F27"), CellRangeAddress.valueOf("A28:F28"), CellRangeAddress.valueOf("A29:F29") }; /* Applying above created rule formatting to cells */ sheetCF.addConditionalFormatting(regionsAction, rule2); sheetCF.addConditionalFormatting(regionsAdv, rule3); /* Setting coloumn header values */ int mainCellIndex = 0; CellStyle style4 = workbook.createCellStyle(); XSSFFont my_font2 = (XSSFFont) workbook.createFont(); my_font2.setBold(true); style4.setFont(my_font2); rowMain.setRowStyle(style4); rowMain.createCell(mainCellIndex++).setCellValue("SNO"); rowMain.createCell(mainCellIndex++).setCellValue("Genre"); rowMain.createCell(mainCellIndex++).setCellValue("Rating"); rowMain.createCell(mainCellIndex++).setCellValue("Movie Name"); rowMain.createCell(mainCellIndex++).setCellValue("Director"); rowMain.createCell(mainCellIndex++).setCellValue("Release Date"); /* populating cell values */ int rowIndex = 4; int sno = 1; for (Song song : songList) { if (song.getSno() != 0) { Row row = songsSheet.createRow(rowIndex++); int cellIndex = 0; /* first place in row is Sno */ row.createCell(cellIndex++).setCellValue(sno++); /* second place in row is Genre */ row.createCell(cellIndex++).setCellValue(song.getGenre()); /* third place in row is Critic score */ row.createCell(cellIndex++).setCellValue(song.getCriticscore()); /* fourth place in row is Album name */ row.createCell(cellIndex++).setCellValue(song.getAlbumname()); /* fifth place in row is Artist */ row.createCell(cellIndex++).setCellValue(song.getArtist()); /* sixth place in row is marks in date */ if (song.getReleasedate() != null) { Cell date = row.createCell(cellIndex++); DataFormat format = workbook.createDataFormat(); CellStyle dateStyle = workbook.createCellStyle(); dateStyle.setDataFormat(format.getFormat("dd-MMM-yyyy")); date.setCellStyle(dateStyle); date.setCellValue(song.getReleasedate()); /* auto-resizing columns */ songsSheet.autoSizeColumn(6); songsSheet.autoSizeColumn(5); songsSheet.autoSizeColumn(4); songsSheet.autoSizeColumn(3); songsSheet.autoSizeColumn(2); } } } /* writing this workbook to excel file. */ try { FileOutputStream fos = new FileOutputStream(FILE_PATH); workbook.write(fos); fos.close(); System.out.println(FILE_PATH + " is successfully written"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.WorkbooklExportProcessor.java
License:Apache License
public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr, DateTimeHelper dth) {// w w w . j av a 2s . c o m try { String strFileName = uis.getDownloadFileName(); Workbook wbCurrent = null; if (strFileName.toLowerCase().endsWith(".xlsx")) { wbCurrent = new XSSFWorkbook(); } else { wbCurrent = new HSSFWorkbook(); } HashMap<String, CellStyle> hsCS = new HashMap<String, CellStyle>(); CreationHelper cr = wbCurrent.getCreationHelper(); CellStyle csDate = wbCurrent.createCellStyle(); csDate.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDate().toPattern())); CellStyle csDateTime = wbCurrent.createCellStyle(); csDateTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFDateTime().toPattern())); CellStyle csTime = wbCurrent.createCellStyle(); csTime.setDataFormat(cr.createDataFormat().getFormat(dth.getDFTime().toPattern())); hsCS.put("DATE", csDate); hsCS.put("TIME", csTime); hsCS.put("DATETIME", csDateTime); Sheet sh = wbCurrent.createSheet("SVE Export"); int nRowCount = 0; // BUILDING HEADER if (uis.isIncludeHeader()) { Row rw = sh.createRow(nRowCount); int nCol = 0; for (ExportColumn expColumn : expModel.getColumns()) { rw.createCell(nCol).setCellValue(expColumn.getColumnName()); nCol++; } nRowCount++; } // Processing Values for (ExportDataRow expRow : expModel.getRows()) { Row rw = sh.createRow(nRowCount); int nCol = 0; for (ExportColumn expColumn : expModel.getColumns()) { Cell clCurrent = rw.createCell(nCol); setCellValue(expRow.getValue(expColumn.getPosition()), clCurrent, expColumn, hsCS); nCol++; } nRowCount++; } for (int nCol = 0; nCol < expModel.getColumns().size(); nCol++) { sh.autoSizeColumn(nCol); } if (strFileName.toLowerCase().endsWith(".xlsx")) { hsr.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); } else if (strFileName.toLowerCase().endsWith("xls")) { hsr.setContentType("application/vnd.ms-excel"); } else { hsr.setContentType("application/octet-stream"); } hsr.addHeader("Content-disposition", "inline; filename=\"" + strFileName + "\""); OutputStream os = hsr.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); wbCurrent.write(bos); bos.writeTo(os); os.close(); } catch (Exception e) { ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (Workbook Export)", e); } }
From source file:biz.webgate.dominoext.poi.component.kernel.WorkbookProcessor.java
License:Apache License
public void setCellValue(Sheet shProcess, int nRow, int nCol, Object objValue, boolean isFormula, PoiCellStyle pCellStyle) {//from w w w .j a v a 2s . co m // Logger logCurrent = // LoggerFactory.getLogger(WorkbookProcessor.class.getCanonicalName()); try { Row rw = shProcess.getRow(nRow); if (rw == null) { // logCurrent.finest("Create Row"); rw = shProcess.createRow(nRow); } Cell c = rw.getCell(nCol); if (c == null) { // logCurrent.finest("Create Cell"); c = rw.createCell(nCol); } if (isFormula) { c.setCellFormula((String) objValue); } else { if (objValue instanceof Double) { c.setCellValue((Double) objValue); } else if (objValue instanceof Integer) { c.setCellValue((Integer) objValue); } else { if (objValue instanceof Date) { c.setCellValue((Date) objValue); } else { c.setCellValue("" + objValue); } } } // *** STYLE CONFIG Since V 1.1.7 *** if (pCellStyle != null) { checkStyleConstantValues(); if (pCellStyle.getCellStyle() != null) { c.setCellStyle(pCellStyle.getCellStyle()); } else { CellStyle style = shProcess.getWorkbook().createCellStyle(); if (pCellStyle.getAlignment() != null) style.setAlignment(m_StyleConstantValues.get(pCellStyle.getAlignment())); if (pCellStyle.getBorderBottom() != null) style.setBorderBottom(m_StyleConstantValues.get(pCellStyle.getBorderBottom())); if (pCellStyle.getBorderLeft() != null) style.setBorderLeft(m_StyleConstantValues.get(pCellStyle.getBorderLeft())); if (pCellStyle.getBorderRight() != null) style.setBorderRight(m_StyleConstantValues.get(pCellStyle.getBorderRight())); if (pCellStyle.getBorderTop() != null) style.setBorderTop(m_StyleConstantValues.get(pCellStyle.getBorderTop())); if (pCellStyle.getBottomBorderColor() != null) style.setBottomBorderColor( IndexedColors.valueOf(pCellStyle.getBottomBorderColor()).getIndex()); if (pCellStyle.getDataFormat() != null) { DataFormat format = shProcess.getWorkbook().createDataFormat(); style.setDataFormat(format.getFormat(pCellStyle.getDataFormat())); } if (pCellStyle.getFillBackgroundColor() != null) style.setFillBackgroundColor( IndexedColors.valueOf(pCellStyle.getFillBackgroundColor()).getIndex()); if (pCellStyle.getFillForegroundColor() != null) style.setFillForegroundColor( IndexedColors.valueOf(pCellStyle.getFillForegroundColor()).getIndex()); if (pCellStyle.getFillPattern() != null) style.setFillPattern(m_StyleConstantValues.get(pCellStyle.getFillPattern())); // Create a new font and alter it. Font font = shProcess.getWorkbook().createFont(); if (pCellStyle.getFontBoldweight() != null) font.setBoldweight(m_StyleConstantValues.get(pCellStyle.getFontBoldweight())); if (pCellStyle.getFontColor() != null) font.setColor(IndexedColors.valueOf(pCellStyle.getFontColor()).getIndex()); if (pCellStyle.getFontHeightInPoints() != 0) font.setFontHeightInPoints(pCellStyle.getFontHeightInPoints()); if (pCellStyle.getFontName() != null) font.setFontName(pCellStyle.getFontName()); if (pCellStyle.isFontItalic()) font.setItalic(pCellStyle.isFontItalic()); if (pCellStyle.isFontStrikeout()) font.setStrikeout(pCellStyle.isFontStrikeout()); if (pCellStyle.getFontUnderline() != null) font.setUnderline(m_StyleByteConstantValues.get(pCellStyle.getFontUnderline())); if (pCellStyle.getFontTypeOffset() != null) font.setTypeOffset(m_StyleConstantValues.get(pCellStyle.getFontTypeOffset())); // Set Font style.setFont(font); if (pCellStyle.isHidden()) style.setHidden(pCellStyle.isHidden()); if (pCellStyle.getIndention() != null) style.setIndention(m_StyleConstantValues.get(pCellStyle.getIndention())); if (pCellStyle.getLeftBorderColor() != null) style.setLeftBorderColor(IndexedColors.valueOf(pCellStyle.getLeftBorderColor()).getIndex()); if (pCellStyle.isLocked()) style.setLocked(pCellStyle.isLocked()); if (pCellStyle.getRightBorderColor() != null) style.setRightBorderColor( IndexedColors.valueOf(pCellStyle.getRightBorderColor()).getIndex()); if (pCellStyle.getRotation() != 0) style.setRotation(pCellStyle.getRotation()); if (pCellStyle.getTopBorderColor() != null) style.setTopBorderColor(IndexedColors.valueOf(pCellStyle.getTopBorderColor()).getIndex()); if (pCellStyle.getVerticalAlignment() != null) style.setVerticalAlignment(m_StyleConstantValues.get(pCellStyle.getVerticalAlignment())); if (pCellStyle.isWrapText()) style.setWrapText(pCellStyle.isWrapText()); c.setCellStyle(style); pCellStyle.setCellStyle(style); } } } catch (Exception e) { e.printStackTrace(); } }