@Test public void rotatedText() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); CellStyle style1 = workbook.createCellStyle(); style1.setRotation((short) 90); Cell cell0 = row.createCell(0); cell0.setCellValue("Apache Software Foundation"); cell0.setCellStyle(style1); Cell cell1 = row.createCell(1); cell1.setCellValue("Apache Software Foundation"); for (int i = 0; i < 2; i++) sheet.autoSizeColumn(i); int w0 = sheet.getColumnWidth(0); int w1 = sheet.getColumnWidth(1); assertTrue( w0 * 5 < w1); // rotated text occupies at least five times less horizontal space than normal // text workbook.close(); }
private void makeCellAutosizeAndBold(Workbook wb, Row row) { CellStyle style = wb.createCellStyle(); Font font = wb.createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); for (int i = 0; i < row.getLastCellNum(); i++) { row.getCell(i).setCellStyle(style); } makeCellsAutosize(wb, row); }
/** * セルの縮小して全体を表示する * * @param nRow 行データ * @return 有効列数 */ public static void setShrinkToFitForCell(XSSFWorkbook wb, XSSFSheet sheet, int nRow, int nCol) { XSSFRow row = OoxmlUtil.getRowAnyway(sheet, nRow); XSSFCell cell = OoxmlUtil.getCellAnyway(row, nCol); CellStyle styletmp = cell.getCellStyle(); CellStyle newStyletmp = wb.createCellStyle(); newStyletmp.cloneStyleFrom(styletmp); newStyletmp.setWrapText(false); // 折り返して全体を表示する newStyletmp.setShrinkToFit(true); // 縮小して全体を表示する cell.setCellStyle(newStyletmp); }
@Test public void numericCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); DataFormat df = workbook.getCreationHelper().createDataFormat(); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); row.createCell(0) .setCellValue(0); // getCachedFormulaResult() returns 0 for not evaluated formula cells row.createCell(1).setCellValue(10); row.createCell(2).setCellValue("10"); row.createCell(3).setCellFormula("(A1+B1)*1.0"); // a formula that returns '10' Cell cell4 = row.createCell(4); // numeric cell with a custom style CellStyle style4 = workbook.createCellStyle(); style4.setDataFormat(df.getFormat("0.0000")); cell4.setCellStyle(style4); cell4.setCellValue(10); // formatted as '10.0000' row.createCell(5).setCellValue("10.0000"); // autosize not-evaluated cells, formula cells are sized as if the result is 0 for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); assertTrue( sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' assertEquals( sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // 10 and '10' should be sized equally assertEquals( sheet.getColumnWidth(3), sheet.getColumnWidth(0)); // formula result is unknown, the width is calculated for '0' assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' // evaluate formulas and re-autosize evaluateWorkbook(workbook); for (int i = 0; i < 6; i++) sheet.autoSizeColumn(i); assertTrue( sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width of '0' is less then width of '10' assertEquals( sheet.getColumnWidth(1), sheet.getColumnWidth(2)); // columns 1, 2 and 3 should have the same width assertEquals( sheet.getColumnWidth(2), sheet.getColumnWidth(3)); // columns 1, 2 and 3 should have the same width assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(5)); // 10.0000 and '10.0000' workbook.close(); }
private void makeTemporalCell(Cell retVal, Date cellObj, String format) { CreationHelper creationHelper = workbook.getCreationHelper(); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat(format)); retVal.setCellStyle(cellStyle); if (null != cellObj) { Calendar calendar = Calendar.getInstance(); calendar.setTime((Date) cellObj); retVal.setCellValue(calendar); } }
protected org.zkoss.poi.ss.usermodel.Font getPoiFontFromRichText( Workbook book, Cell cell, RichTextString rstr, int run) { if (run < 0) return null; // ZSS-1138 org.zkoss.poi.ss.usermodel.Font font = rstr instanceof HSSFRichTextString ? book.getFontAt(((HSSFRichTextString) rstr).getFontOfFormattingRun(run)) : ((XSSFRichTextString) rstr).getFontOfFormattingRun((XSSFWorkbook) book, run); if (font == null) { CellStyle style = cell.getCellStyle(); short fontIndex = style != null ? style.getFontIndex() : (short) 0; return book.getFontAt(fontIndex); } return font; }
@Override public void setDateTimePattern(String dateTimePattern) { this.dateTimePattern = dateTimePattern; DateTimeConverter dtConverter = (DateTimeConverter) converters.lookup(Date.class); dtConverter.setDateTimePattern(dateTimePattern); dateCellStyle = workbook.createCellStyle(); CreationHelper helper = workbook.getCreationHelper(); dateCellStyle.setDataFormat(helper.createDataFormat().getFormat(dateTimePattern)); }
@Test public void stringCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); Row row = sheet.createRow(0); Font defaultFont = workbook.getFontAt((short) 0); CellStyle style1 = workbook.createCellStyle(); Font font1 = workbook.createFont(); font1.setFontHeight((short) (2 * defaultFont.getFontHeight())); style1.setFont(font1); row.createCell(0).setCellValue("x"); row.createCell(1).setCellValue("xxxx"); row.createCell(2).setCellValue("xxxxxxxxxxxx"); row.createCell(3) .setCellValue("Apache\nSoftware Foundation"); // the text is splitted into two lines row.createCell(4).setCellValue("Software Foundation"); Cell cell5 = row.createCell(5); cell5.setCellValue("Software Foundation"); cell5.setCellStyle( style1); // same as in column 4 but the font is twice larger than the default font for (int i = 0; i < 10; i++) sheet.autoSizeColumn(i); assertTrue( 2 * sheet.getColumnWidth(0) < sheet.getColumnWidth(1)); // width is roughly proportional to the number of characters assertTrue(2 * sheet.getColumnWidth(1) < sheet.getColumnWidth(2)); assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); boolean ignoreFontSizeX2 = JvmBugs.hasLineBreakMeasurerBug(); assertTrue( ignoreFontSizeX2 || sheet.getColumnWidth(5) > sheet.getColumnWidth(4)); // larger font results in a wider column width workbook.close(); }
protected SFont importFont(CellStyle poiCellStyle) { SFont font = null; final short fontIndex = poiCellStyle.getFontIndex(); if (importedFont.containsKey(fontIndex)) { font = importedFont.get(fontIndex); } else { Font poiFont = workbook.getFontAt(fontIndex); font = createZssFont(poiFont); importedFont.put(fontIndex, font); // ZSS-677 } return font; }
public static HSSFCellStyle getNewStyles( HSSFWorkbook workBook, CellStyle cellStyle, HSSFFont font) { HSSFCellStyle style = workBook.createCellStyle(); // 对齐方式 style.setAlignment(cellStyle.getAlignment()); style.setVerticalAlignment(cellStyle.getVAlignment()); // 设置自动换行 style.setWrapText(cellStyle.getWrapText()); style.setHidden(cellStyle.getHidden()); // 数据格式 style.setDataFormat(cellStyle.getDataFormate()); style.setLocked(cellStyle.getLocked()); // 文本旋转 请注意,这里的Rotation取值是从-90到90,而不是0-180度 style.setRotation(cellStyle.getRotation()); // 文本缩进 style.setIndention(cellStyle.getIndention()); // 设置字体 style.setFont(font); return style; }
/** * Compute width of a single cell * * @param cell the cell whose width is to be calculated * @param defaultCharWidth the width of a single character * @param formatter formatter used to prepare the text to be measured * @param useMergedCells whether to use merged cells * @return the width in pixels */ public static double getCellWidth( Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells) { Sheet sheet = cell.getSheet(); Workbook wb = sheet.getWorkbook(); Row row = cell.getRow(); int column = cell.getColumnIndex(); int colspan = 1; for (int i = 0; i < sheet.getNumMergedRegions(); i++) { CellRangeAddress region = sheet.getMergedRegion(i); if (containsCell(region, row.getRowNum(), column)) { if (!useMergedCells) { // If we're not using merged cells, skip this one and move on to the next. return -1; } cell = row.getCell(region.getFirstColumn()); colspan = 1 + region.getLastColumn() - region.getFirstColumn(); } } CellStyle style = cell.getCellStyle(); int cellType = cell.getCellType(); // for formula cells we compute the cell width for the cached formula result if (cellType == Cell.CELL_TYPE_FORMULA) cellType = cell.getCachedFormulaResultType(); Font font = wb.getFontAt(style.getFontIndex()); AttributedString str; TextLayout layout; double width = -1; if (cellType == Cell.CELL_TYPE_STRING) { RichTextString rt = cell.getRichStringCellValue(); String[] lines = rt.getString().split("\\n"); for (int i = 0; i < lines.length; i++) { String txt = lines[i] + defaultChar; str = new AttributedString(txt); copyAttributes(font, str, 0, txt.length()); if (rt.numFormattingRuns() > 0) { // TODO: support rich text fragments } layout = new TextLayout(str.getIterator(), fontRenderContext); if (style.getRotation() != 0) { /* * Transform the text using a scale so that it's height is increased by a multiple of the leading, * and then rotate the text before computing the bounds. The scale results in some whitespace around * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but * is added by the standard Excel autosize. */ AffineTransform trans = new AffineTransform(); trans.concatenate( AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0)); trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple)); width = Math.max( width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } else { width = Math.max( width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } } } else { String sval = null; if (cellType == Cell.CELL_TYPE_NUMERIC) { // Try to get it formatted to look the same as excel try { sval = formatter.formatCellValue(cell, dummyEvaluator); } catch (Exception e) { sval = String.valueOf(cell.getNumericCellValue()); } } else if (cellType == Cell.CELL_TYPE_BOOLEAN) { sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase(); } if (sval != null) { String txt = sval + defaultChar; str = new AttributedString(txt); copyAttributes(font, str, 0, txt.length()); layout = new TextLayout(str.getIterator(), fontRenderContext); if (style.getRotation() != 0) { /* * Transform the text using a scale so that it's height is increased by a multiple of the leading, * and then rotate the text before computing the bounds. The scale results in some whitespace around * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but * is added by the standard Excel autosize. */ AffineTransform trans = new AffineTransform(); trans.concatenate( AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0)); trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple)); width = Math.max( width, ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } else { width = Math.max( width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth) + cell.getCellStyle().getIndention()); } } } return width; }
public static void writeExcelFile(String fileLocation) { try { FileOutputStream fileOut = new FileOutputStream(fileLocation); HSSFWorkbook workbook = new HSSFWorkbook(); Font bold = workbook.createFont(); // Create font bold.setBoldweight(Font.BOLDWEIGHT_BOLD); // Make font bold CellStyle correctCell = workbook.createCellStyle(); correctCell.setFillForegroundColor(HSSFColor.GREEN.index); correctCell.setFillBackgroundColor(HSSFColor.GREEN.index); correctCell.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle incorrectCell = workbook.createCellStyle(); incorrectCell.setFillForegroundColor(HSSFColor.RED.index); incorrectCell.setFillBackgroundColor(HSSFColor.RED.index); incorrectCell.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle classificationCells = workbook.createCellStyle(); classificationCells.setFillForegroundColor(HSSFColor.YELLOW.index); classificationCells.setFillBackgroundColor(HSSFColor.YELLOW.index); classificationCells.setFillPattern(CellStyle.SOLID_FOREGROUND); CellStyle attributeNameCells = workbook.createCellStyle(); attributeNameCells.setFont(bold); CellStyle classificationAttributeCell = workbook.createCellStyle(); classificationAttributeCell.setFillForegroundColor(HSSFColor.YELLOW.index); classificationAttributeCell.setFillBackgroundColor(HSSFColor.YELLOW.index); classificationAttributeCell.setFillPattern(CellStyle.SOLID_FOREGROUND); classificationAttributeCell.setFont(bold); Sheet worksheet = workbook.createSheet("Results"); Row currRow = worksheet.createRow(0); for (int attribute = 0; attribute < metadataLL.size() + 1; attribute++) { Cell currCell = currRow.createCell(attribute); if (attribute < metadataLL.size()) { currCell.setCellValue(metadataLL.get(attribute)[0]); if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellStyle(classificationAttributeCell); } else { currCell.setCellStyle(attributeNameCells); } } else { currCell.setCellValue("Guessed Classification"); currCell.setCellStyle(attributeNameCells); } } int correct = 0; int incorrect = 0; for (int node = 0; node < testDataLL.size(); node++) { currRow = worksheet.createRow(node + 1); // Offset by one since first row is header data int classifierCompleted = 0; // Necessary for if data does not end in classifier for (int attribute = 0; attribute < metadataLL.size() + 2; attribute++) // +1 for the row for guessed data +1 for the row that contains { Cell currCell = currRow.createCell(attribute); if (attribute < metadataLL.size()) // Print testingData { if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellValue(actualClassifications.get(node)); currCell.setCellStyle(classificationCells); classifierCompleted++; } else { currCell.setCellValue(testDataLL.get(node)[attribute - classifierCompleted]); } } else if (attribute == metadataLL.size()) // Print guessed classification { currCell.setCellValue(guessedClassifications.get(node)); if (guessedClassifications.get(node).compareTo(actualClassifications.get(node)) == 0) { currCell.setCellStyle(correctCell); correct++; } else { currCell.setCellStyle(incorrectCell); incorrect++; } if (node == testDataLL.size() - 1) // If this is the last loop { double precentRight = (double) correct / (correct + incorrect); currRow = worksheet.createRow(node + 2); currCell = currRow.createCell(attribute); currCell.setCellValue(precentRight); if (precentRight > .90) { correctCell.setDataFormat(workbook.createDataFormat().getFormat("0.000%")); currCell.setCellStyle(correctCell); } else { incorrectCell.setDataFormat(workbook.createDataFormat().getFormat("0.000%")); currCell.setCellStyle(incorrectCell); } } } else if (attribute == metadataLL.size() + 1) // Print potential bad training data if the flag is true { if (unseenDataFlag.get(node)) { currCell.setCellValue( "This node an attribute value not in the training set, classifier selected is based on most frequent classifier. If laplacian smoothing is 1 or more this likely wont happen"); // TODO make this a bit shorter } } } } worksheet = workbook.createSheet("Training Data"); currRow = worksheet.createRow(0); for (int attribute = 0; attribute < metadataLL.size(); attribute++) { Cell currCell = currRow.createCell(attribute); currCell.setCellValue(metadataLL.get(attribute)[0]); currCell.setCellStyle(attributeNameCells); } for (int node = 0; node < trainingDataLL.size(); node++) { currRow = worksheet.createRow(node + 1); // Offset by one since first row is header data int classifierCompleted = 0; // Necessary for if data does not end in classifier for (int attribute = 0; attribute < metadataLL.size(); attribute++) { Cell currCell = currRow.createCell(attribute); if (metadataLL.get(attribute)[2].compareTo("classifier") == 0) { currCell.setCellValue(knownClassifications.get(node)); classifierCompleted++; } else { currCell.setCellValue(trainingDataLL.get(node)[attribute - classifierCompleted]); } } } worksheet = workbook.createSheet("Likelihood"); currRow = worksheet.createRow(0); int largestAttributeSize = 0; for (int attribute = 0; attribute < classifier.size(); attribute++) { if (classifier.get(attribute).size() > largestAttributeSize) { largestAttributeSize = classifier.get(attribute).size(); } } // Label attributes along the top for (int i = 0; i < metadataLL.size(); i++) { if (i == 0) { Cell currCell = currRow.createCell(i); // currCell.setCellValue("Attributes"); currCell.setCellStyle(attributeNameCells); } else { Cell currCell = currRow.createCell(i); currCell.setCellValue( metadataLL .get(i - 1)[0]); // -1 since the first cell does not contain a attribute name currCell.setCellStyle(attributeNameCells); } } // List possible classifications on the side and classification likelihoods at the end for (int i = 0; i < (largestAttributeSize * (classificationTypes.size() + 1) + classificationTypes.size() + 1); i++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { // +classificationTypes.size() so we can list the classification types likelihood at the end currRow = worksheet.createRow(i + 1); // +1 since first row is attribute names Cell currCell = currRow.createCell(0); int currentClassificationType = i % (classificationTypes.size() + 1); // +1 since the first row of each stride lists each attributes string of // what occurrence the likelihoods are displaying // List the classification type of each row along the side if (i < largestAttributeSize * (classificationTypes.size() + 1)) // +1 since the first row of each stride lists each attributes string of // what occurrence the likelihoods are displaying { for (int j = 0; j < classificationTypes.size() + 1; j++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { if (currentClassificationType == 0) { // Do nothing for now may have it say something later } else if (currentClassificationType == j) { currCell.setCellValue( classificationTypes.get( j - 1)); // -1 since the first cell does not contain a classification type } } } else // List the likelihood of each classification at the end { for (int j = 0; j < classificationTypes.size() + 1; j++) // +1 since the first row of each stride lists each attributes string of what // occurrence the likelihoods are displaying { if (currentClassificationType == 0) { // Do nothing for now may have it say value later } else if (currentClassificationType == j) { currCell.setCellValue( "Likelihood of: " + classificationTypes.get(j - 1) + " is " + classificationLikelihood.get( j - 1)); // -1 since the first cell does not contain a classification type } } } currCell.setCellStyle(attributeNameCells); } // List the data for (int attribute = 0; attribute < classifier.size(); attribute++) { for (int occurrences = 0; occurrences < classifier.get(attribute).size(); occurrences++) { for (int classification = 0; classification < classifier.get(attribute).get(occurrences).length; classification++) { currRow = worksheet.getRow( (occurrences * classifier.get(attribute).get(occurrences).length + classification) + 1); // +1 since first row is attribute names Cell currCell = currRow.createCell( (attribute) + 1); // TODO figure out why this errors out at i:0 j:4 k:0 // largestAttributeSize:105 on kidney dataset currCell.setCellValue(classifier.get(attribute).get(occurrences)[classification]); } } } workbook.write(fileOut); workbook.close(); workbook.close(); } catch (FileNotFoundException e) { System.out.println("Error file not found"); e.printStackTrace(); System.exit(0); } catch (IOException e) { System.out.println("Unable to output file, is the output destination writelocked?"); e.printStackTrace(); System.exit(0); } }
private static Map createStyles(Workbook wb) { Map styles = new HashMap(); Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 14); titleFont.setFontName("Trebuchet MS"); CellStyle style = wb.createCellStyle(); style.setFont(titleFont); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); styles.put("title", style); Font itemFont = wb.createFont(); itemFont.setFontHeightInPoints((short) 9); itemFont.setFontName("Trebuchet MS"); style = wb.createCellStyle(); style.setAlignment((short) 1); style.setFont(itemFont); styles.put("item_left", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); styles.put("item_right", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat( wb.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)")); styles.put("input_$", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0.000%")); styles.put("input_%", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0")); styles.put("input_i", style); style = wb.createCellStyle(); style.setAlignment((short) 2); style.setFont(itemFont); style.setDataFormat(wb.createDataFormat().getFormat("m/d/yy")); styles.put("input_d", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("$##,##0.00")); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern((short) 1); styles.put("formula_$", style); style = wb.createCellStyle(); style.setAlignment((short) 3); style.setFont(itemFont); style.setBorderRight((short) 7); style.setRightBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderLeft((short) 7); style.setLeftBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setBorderTop((short) 7); style.setTopBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setDataFormat(wb.createDataFormat().getFormat("0")); style.setBorderBottom((short) 7); style.setBottomBorderColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern((short) 1); styles.put("formula_i", style); return styles; }
@Test public void test_poi() { final int rowNum = 27; final int colNum = 15; HSSFWorkbook wb = null; Sheet sheet = null; String today = "2013/8/31"; String sign = "Month to date"; String[] titles = { "", "", "", "Chinapay eMail\r\n 商城总计", "Japan Page\r\n 日本馆首页", "Taiwan Page\r\n 台湾馆首页", "USA Page\r\n 美国馆首页", "Anhui Page\r\n 安徽馆首页", "China Page\r\n 中国馆首页" }; String[] colNames = { "", "Page View (PV)\r\n 浏览量", "Unique Visitor (UV)\r\n 独立访客", "Completed Orders\r\n 确认订单", "Transaction Amount\r\n 交易金额", "1st Top Seller\r\n 最佳销量", "Unit Price 单价", "Qty Sold 销量", "2nd Top Seller\r\n 第二销量", "Unit Price 单价", "Qty Sold 销量", "3rd Top Seller\r\n 第三销量", "Unit Price 单价", "Qty Sold 销量", "1st Top Seller\r\n 最佳销量", "Unit Price 单价", "Qty Sold 销量", "2nd Top Seller\r\n 第二销量", "Unit Price 单价", "Qty Sold 销量", "3rd Top Seller\r\n 第三销量", "Unit Price 单价", "Qty Sold 销量" }; int n = 0; int len = 1; String fileName = "D:/日报.xls"; File f = new File(fileName); ByteArrayOutputStream byteArrayOut = null; BufferedImage bufferImg = null; String[] jpgUrls = { "http://img.chinapay.com/data/files/store_37452/goods_93/small_201303271804531386.jpg", "http://img.chinapay.com/data/files/store_44066/goods_37/201308280953576580.jpg", "http://img.chinapay.com/data/files/store_289253/goods_95/small_201309031434558044.jpg", "http://img.chinapay.com/data/files/store_289253/goods_180/small_201309031403003861.jpg", "http://img.chinapay.com/data/files/store_37452/goods_98/small_201309121508186810.jpg", "http://img.chinapay.com/data/files/store_37452/goods_24/small_201301241133447193.jpg" }; String[] https = { "http://emall.chinapay.com/goods/37452/1010000109792.html", "http://emall.chinapay.com/goods/44066/1010000119323.html", "http://emall.chinapay.com/goods/289253/1010000119621.html?jpsv=laoxcashback6", "http://emall.chinapay.com/goods/289253/1010000119627.html?jpsv=laoxcashback6", "http://emall.chinapay.com/goods/37452/1010000120588.html", "http://emall.chinapay.com/goods/37452/1010000107096.html" }; URL url = null; HSSFHyperlink link = null; HSSFPatriarch patri = null; HSSFClientAnchor anchor = null; try { if (!f.exists()) { wb = new HSSFWorkbook(); } else { FileInputStream in = new FileInputStream(fileName); wb = new HSSFWorkbook(in); } CellStyle style = wb.createCellStyle(); style.setFillForegroundColor(HSSFCellStyle.THIN_BACKWARD_DIAG); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // style.setLeftBorderColor(HSSFColor.RED.index); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框 style.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框 style.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框 style.setWrapText(true); sheet = wb.createSheet("sheet " + ((int) (100000 * Math.random()))); // 设置列的宽度 sheet.setDefaultColumnWidth(20); sheet.setDefaultRowHeight((short) 400); Row row = null; Cell cell = null; for (int r = 0; r < rowNum; r++) { row = sheet.createRow(r); // 设置第1行当高度 if (r == 0) { row.setHeightInPoints(30); } // 设置第2列以后的宽度(即列号>=2的列,列号从0开始) if (r >= 2) { sheet.setColumnWidth(r, 3020); } for (int c = 0; c < colNum; c++) { cell = row.createCell(c); cell.setCellStyle(style); // 处理第一行 if (r == 0) { sheet.addMergedRegion(new CellRangeAddress(r, r, 3, 4)); sheet.addMergedRegion(new CellRangeAddress(r, r, 5, 6)); sheet.addMergedRegion(new CellRangeAddress(r, r, 7, 8)); sheet.addMergedRegion(new CellRangeAddress(r, r, 9, 10)); sheet.addMergedRegion(new CellRangeAddress(r, r, 11, 12)); sheet.addMergedRegion(new CellRangeAddress(r, r, 13, 14)); if (c < 3) { cell.setCellValue(titles[n++]); } else { if ((c & 1) == 1) { System.out.println("c===" + c); cell.setCellValue(titles[n++]); } } } // 处理第2~8行 if (r > 0 && r <= 8) { if (c == 0) { if (r < 8 && (r & 1) == 1) { sheet.addMergedRegion(new CellRangeAddress(r, r + 1, 0, 0)); System.err.println("row----->" + r + " len----->" + (len)); cell.setCellValue(colNames[len++]); } else if (r > 8) { System.out.println("len+++++++++>" + (len)); cell.setCellValue(colNames[len++]); } } else if (c == 1) { cell.setCellValue((r & 1) == 1 ? today : sign); System.err.println("r---->" + r); } else if (c == 2) { cell.setCellValue((r & 1) == 1 ? "当天" : "当月"); } else { if ((c & 1) == 1) { sheet.addMergedRegion(new CellRangeAddress(r, r, c, c + 1)); cell.setCellValue("26.55"); } } } // 处理第8行以后的数据(不包括第8行) if (r > 8) { // 设置列高(图片的高度) if (r % 3 == 0) { sheet.getRow(r).setHeightInPoints(110); } if (c == 0) { System.err.println("r---->" + r); cell.setCellValue(colNames[r - 4]); } else if (c == 1) { cell.setCellValue((r % 3) == 0 ? today : (r % 3 == 1 ? "PV 浏览量" : "Total Sales 总额")); } else if (c == 2) { if (r % 9 == 0) { sheet.addMergedRegion(new CellRangeAddress(r, r + 8, c, c)); if (r / 9 == 1) cell.setCellValue("当天"); else cell.setCellValue("当月"); cell.setCellStyle(style); } } else { if (r % 3 == 0) { if ((c & 1) == 1) { sheet.addMergedRegion(new CellRangeAddress(r, r, c, c + 1)); // 添加远程图片信息 url = new URL(jpgUrls[(c - 3) / 2]); bufferImg = ImageIO.read(url.openStream()); byteArrayOut = new ByteArrayOutputStream(); ImageIO.write(bufferImg, "jpg", byteArrayOut); patri = (HSSFPatriarch) sheet.createDrawingPatriarch(); anchor = new HSSFClientAnchor(10, 2, 0, 0, (short) c, r, (short) (c + 2), r + 1); patri.createPicture( anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)); bufferImg.flush(); // link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); // System.out.println(https[(c-3)/2]); // link.setAddress("fetion/"+https[(c-3)/2]); // cell.setHyperlink(link); // link = (HSSFHyperlink) cell.getHyperlink(); // link = new HSSFHyperlink(HSSFHyperlink.LINK_URL); // link.setAddress(https[(c-3)/2]); // cell.setHyperlink(link); } } else { if ((c & 1) == 0) { link = wb.getCreationHelper().createHyperlink(Hyperlink.LINK_URL); link.setAddress(https[(c - 3) / 2]); cell.setHyperlink(link); // 设定单元格的链接 cell.setCellValue("图片超链接"); } else { cell.setCellValue("Number"); } } } } } } // 备注 row = sheet.createRow(27); cell = row.createCell(0); sheet.addMergedRegion(new CellRangeAddress(27, 27, 0, colNum - 1)); cell.setCellValue("* 销量排名不以销售金额计算,如相同销量者,则以PV量少者为优胜"); FileOutputStream out = new FileOutputStream(fileName); wb.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("++++++++++++ EXCEl文件 success +++++++++++++"); }
public static XSSFCellStyle getNewStyle( XSSFWorkbook workBook, CellStyle cellStyle, XSSFFont font) { XSSFCellStyle style = workBook.createCellStyle(); // 对齐方式 style.setAlignment(cellStyle.getAlignment()); style.setVerticalAlignment(cellStyle.getVAlignment()); // 设置背景颜色 // 最好的设置Pattern style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // 单元格背景的显示模式 style.setFillForegroundColor(cellStyle.getColor()); // 单元格背景的显示模式. // style.setFillBackgroundColor(arg0); // 设置边框 style.setBorderBottom(cellStyle.getBorderBottom()); // 下边框 style.setBorderLeft(cellStyle.getBorderLeft()); // 左边框 style.setBorderTop(cellStyle.getBorderTop()); // 上边框 style.setBorderRight(cellStyle.getBorderRight()); // 右边框 // 设置边框颜色 style.setBottomBorderColor(cellStyle.getBottomBorderColor()); style.setTopBorderColor(cellStyle.getTopBorderColor()); style.setLeftBorderColor(cellStyle.getLeftBorderColor()); style.setRightBorderColor(cellStyle.getRightBorderColor()); // 设置自动换行 style.setWrapText(cellStyle.getWrapText()); style.setHidden(cellStyle.getHidden()); // 数据格式 style.setDataFormat(cellStyle.getDataFormate()); style.setLocked(cellStyle.getLocked()); // 文本旋转 请注意,这里的Rotation取值是从-90到90,而不是0-180度 style.setRotation(cellStyle.getRotation()); // 文本缩进 style.setIndention(cellStyle.getIndention()); // 设置字体 style.setFont(font); return style; }
public File generateXLSResponse(QueryResult queryResult, Locale locale, String baseURL) { File excelFile = new File("export_parts.xls"); // Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); // Create a blank sheet XSSFSheet sheet = workbook.createSheet("Parts Data"); String header = StringUtils.join(queryResult.getQuery().getSelects(), ";"); String[] columns = header.split(";"); Map<Integer, String[]> data = new HashMap<>(); String[] headerFormatted = createXLSHeaderRow(header, columns, locale); data.put(1, headerFormatted); Map<Integer, String[]> commentsData = new HashMap<>(); String[] headerComments = createXLSHeaderRowComments(header, columns); commentsData.put(1, headerComments); List<String> selects = queryResult.getQuery().getSelects(); int i = 1; for (QueryResultRow row : queryResult.getRows()) { i++; data.put(i, createXLSRow(selects, row, baseURL)); commentsData.put(i, createXLSRowComments(selects, row)); } // Iterate over data and write to sheet Set<Integer> keyset = data.keySet(); int rownum = 0; for (Integer key : keyset) { Row row = sheet.createRow(rownum++); String[] objArr = data.get(key); int cellnum = 0; for (String obj : objArr) { Cell cell = row.createCell(cellnum++); cell.setCellValue(obj); } CreationHelper factory = workbook.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); String[] commentsObjArr = commentsData.get(key); cellnum = 0; for (String commentsObj : commentsObjArr) { if (commentsObj.length() > 0) { Cell cell = row.getCell(cellnum) != null ? row.getCell(cellnum) : row.createCell(cellnum); // When the comment box is visible, have it show in a 1x3 space ClientAnchor anchor = factory.createClientAnchor(); anchor.setCol1(cell.getColumnIndex()); anchor.setCol2(cell.getColumnIndex() + 1); anchor.setRow1(row.getRowNum()); anchor.setRow2(row.getRowNum() + 1); Comment comment = drawing.createCellComment(anchor); RichTextString str = factory.createRichTextString(commentsObj); comment.setString(str); // Assign the comment to the cell cell.setCellComment(comment); } cellnum++; } } // Define header style Font headerFont = workbook.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerFont.setFontHeightInPoints((short) 10); headerFont.setFontName("Courier New"); headerFont.setItalic(true); headerFont.setColor(IndexedColors.WHITE.getIndex()); CellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFont(headerFont); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND); // Set header style for (int j = 0; j < columns.length; j++) { Cell cell = sheet.getRow(0).getCell(j); cell.setCellStyle(headerStyle); if (cell.getCellComment() != null) { String comment = cell.getCellComment().getString().toString(); if (comment.equals(QueryField.CTX_PRODUCT_ID) || comment.equals(QueryField.CTX_SERIAL_NUMBER) || comment.equals(QueryField.PART_MASTER_NUMBER)) { for (int k = 0; k < queryResult.getRows().size(); k++) { Cell grayCell = sheet.getRow(k + 1).getCell(j) != null ? sheet.getRow(k + 1).getCell(j) : sheet.getRow(k + 1).createCell(j); grayCell.setCellStyle(headerStyle); } } } } try { // Write the workbook in file system FileOutputStream out = new FileOutputStream(excelFile); workbook.write(out); out.close(); } catch (Exception e) { LOGGER.log(Level.FINEST, null, e); } return excelFile; }
@Test public void dateCells() throws Exception { Workbook workbook = _testDataProvider.createWorkbook(); fixFonts(workbook); Sheet sheet = workbook.createSheet(); DataFormat df = workbook.getCreationHelper().createDataFormat(); CellStyle style1 = workbook.createCellStyle(); style1.setDataFormat(df.getFormat("m")); CellStyle style3 = workbook.createCellStyle(); style3.setDataFormat(df.getFormat("mmm")); CellStyle style5 = workbook.createCellStyle(); // rotated text style5.setDataFormat(df.getFormat("mmm/dd/yyyy")); Calendar calendar = LocaleUtil.getLocaleCalendar(2010, 0, 1); // Jan 1 2010 Row row = sheet.createRow(0); row.createCell(0).setCellValue(DateUtil.getJavaDate(0)); // default date Cell cell1 = row.createCell(1); cell1.setCellValue(calendar); cell1.setCellStyle(style1); row.createCell(2).setCellValue("1"); // column 1 should be sized as '1' Cell cell3 = row.createCell(3); cell3.setCellValue(calendar); cell3.setCellStyle(style3); row.createCell(4).setCellValue("Jan"); Cell cell5 = row.createCell(5); cell5.setCellValue(calendar); cell5.setCellStyle(style5); row.createCell(6).setCellValue("Jan/01/2010"); Cell cell7 = row.createCell(7); cell7.setCellFormula("DATE(2010,1,1)"); cell7.setCellStyle(style3); // should be sized as 'Jan' // autosize not-evaluated cells, formula cells are sized as if the result is 0 for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' assertTrue( sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' assertEquals( sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' // YK: width of not-evaluated formulas that return data is not determined // POI seems to conevert '0' to Excel date which is the beginng of the Excel's date system // evaluate formulas and re-autosize evaluateWorkbook(workbook); for (int i = 0; i < 8; i++) sheet.autoSizeColumn(i); assertEquals(sheet.getColumnWidth(2), sheet.getColumnWidth(1)); // date formatted as 'm' assertTrue(sheet.getColumnWidth(3) > sheet.getColumnWidth(1)); // 'mmm' is wider than 'm' assertEquals(sheet.getColumnWidth(4), sheet.getColumnWidth(3)); // date formatted as 'mmm' assertTrue( sheet.getColumnWidth(5) > sheet.getColumnWidth(3)); // 'mmm/dd/yyyy' is wider than 'mmm' assertEquals( sheet.getColumnWidth(6), sheet.getColumnWidth(5)); // date formatted as 'mmm/dd/yyyy' assertEquals( sheet.getColumnWidth(4), sheet.getColumnWidth(7)); // date formula formatted as 'mmm' workbook.close(); }
/** * This method process the cells in a <code>Document</code> and generates a portion of the <code> * Document</code>. * * <p>This method assumes that records are sorted by row and then column. * * @param root The <code>Node</code> of the <code>Document</code> we are building that we will * append our cell <code>Node</code> objects. This <code>Node</code> should be a TAG_TABLE * tag. * @throws IOException If any I/O error occurs. */ protected void processCells(Node root) throws IOException { // The current row element Element rowElement = null; // The current cell element Element cellElement = null; // The row number - we may not have any rows (empty sheet) // so set to zero. int row = 0; // The column number - This is the expected column number of // the next cell we are reading. int col = 1; // The number of columns in the spreadsheet int lastColumn = decoder.getNumberOfColumns(); Node autoStylesNode = null; // Loop over all cells in the spreadsheet while (decoder.goToNextCell()) { // Get the row number int newRow = decoder.getRowNumber(); // Is the cell in a new row, or part of the current row? if (newRow != row) { // Make sure that all the cells in the previous row // have been entered. if (col <= lastColumn && rowElement != null) { int numSkippedCells = lastColumn - col + 1; addEmptyCells(numSkippedCells, rowElement); } // log an end row - if we already have a row if (row != 0) { Debug.log(Debug.TRACE, "</tr>"); } // How far is the new row from the last row? int deltaRows = newRow - row; // Check if we have skipped any rows if (deltaRows > 1) { // Add in empty rows addEmptyRows(deltaRows - 1, root, lastColumn); } // Re-initialize column (since we are in a new row) col = 1; // Create an element node for the new row rowElement = doc.createElement(TAG_TABLE_ROW); for (Iterator<ColumnRowInfo> e = decoder.getColumnRowInfos(); e.hasNext(); ) { ColumnRowInfo cri = e.next(); if (cri.isRow() && cri.getRepeated() == newRow - 1) { // We have the correct Row BIFFRecord for this row RowStyle rStyle = new RowStyle( "Default", SxcConstants.ROW_STYLE_FAMILY, SxcConstants.DEFAULT_STYLE, cri.getSize(), null); Style result[] = styleCat.getMatching(rStyle); String styleName; if (result.length == 0) { rStyle.setName("ro" + rowStyles++); styleName = rStyle.getName(); Debug.log(Debug.TRACE, "No existing style found, adding " + styleName); styleCat.add(rStyle); } else { RowStyle existingStyle = (RowStyle) result[0]; styleName = existingStyle.getName(); Debug.log(Debug.TRACE, "Existing style found : " + styleName); } rowElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, styleName); // For now we will not use the repeat column attribute } } // Append the row element to the root node root.appendChild(rowElement); // Update row number row = newRow; Debug.log(Debug.TRACE, "<tr>"); } // Get the column number of the current cell int newCol = decoder.getColNumber(); // Check to see if some columns were skipped if (newCol != col) { // How many columns have we skipped? int numColsSkipped = newCol - col; addEmptyCells(numColsSkipped, rowElement); // Update the column number to account for the // skipped cells col = newCol; } // Lets start dealing with the cell data Debug.log(Debug.TRACE, "<td>"); // Get the cell's contents String cellContents = decoder.getCellContents(); // Get the type of the data in the cell String cellType = decoder.getCellDataType(); // Get the cell format Format fmt = decoder.getCellFormat(); // Create an element node for the cell cellElement = doc.createElement(TAG_TABLE_CELL); Node bodyNode = doc.getElementsByTagName(TAG_OFFICE_BODY).item(0); // Not every document has an automatic style tag autoStylesNode = doc.getElementsByTagName(TAG_OFFICE_AUTOMATIC_STYLES).item(0); if (autoStylesNode == null) { autoStylesNode = doc.createElement(TAG_OFFICE_AUTOMATIC_STYLES); doc.insertBefore(autoStylesNode, bodyNode); } CellStyle tStyle = new CellStyle( "Default", SxcConstants.TABLE_CELL_STYLE_FAMILY, SxcConstants.DEFAULT_STYLE, fmt, null); String styleName; Style result[] = styleCat.getMatching(tStyle); if (result.length == 0) { tStyle.setName("ce" + textStyles++); styleName = tStyle.getName(); Debug.log(Debug.TRACE, "No existing style found, adding " + styleName); styleCat.add(tStyle); } else { CellStyle existingStyle = (CellStyle) result[0]; styleName = existingStyle.getName(); Debug.log(Debug.TRACE, "Existing style found : " + styleName); } cellElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, styleName); // Store the cell data into the appropriate attributes processCellData(cellElement, cellType, cellContents); // Append the cell element to the row node rowElement.appendChild(cellElement); // Append the cellContents as a text node Element textElement = doc.createElement(TAG_PARAGRAPH); cellElement.appendChild(textElement); textElement.appendChild(doc.createTextNode(cellContents)); Debug.log(Debug.TRACE, cellContents); Debug.log(Debug.TRACE, "</td>"); // Increment to the column number of the next expected cell col++; } // Make sure that the last row is padded correctly if (col <= lastColumn && rowElement != null) { int numSkippedCells = lastColumn - col + 1; addEmptyCells(numSkippedCells, rowElement); } // Now write the style catalog to the document if (autoStylesNode != null) { Debug.log(Debug.TRACE, "Well the autostyle node was found!!!"); NodeList nl = styleCat.writeNode(doc, "dummy").getChildNodes(); int nlLen = nl.getLength(); // nl.item reduces the length for (int i = 0; i < nlLen; i++) { autoStylesNode.appendChild(nl.item(0)); } } if (row != 0) { // The sheet does have rows, so write out a /tr Debug.log(Debug.TRACE, "</tr>"); } }
/** * This method traverses a <i>table:table-cell</i> element {@code Node}. * * @param node a <i>table:table-cell</i> {@code Node}. * @throws IOException if any I/O error occurs. */ protected void traverseCell(Node node) throws IOException { NamedNodeMap cellAtt = node.getAttributes(); fmt.clearFormatting(); // Get the type of data in the cell Node tableValueTypeNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_VALUE_TYPE); // Get the number of columns this cell is repeated Node colsRepeatedNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_NUM_COLUMNS_REPEATED); // Get the style type Node tableStyleNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_STYLE_NAME); String styleName = ""; if (tableStyleNode != null) { styleName = tableStyleNode.getNodeValue(); } CellStyle cStyle = null; if (styleName.equalsIgnoreCase("Default")) { Debug.log(Debug.TRACE, "No defined Style Attribute was found"); } else if (styleName.length() != 0) { cStyle = (CellStyle) styleCat.lookup( styleName, SxcConstants.TABLE_CELL_STYLE_FAMILY, null, CellStyle.class); } if (cStyle != null) { Format definedFormat = cStyle.getFormat(); fmt = new Format(definedFormat); } // There is a number of cols repeated attribute if (colsRepeatedNode != null) { // Get the number of times the cell is repeated String colsRepeatedString = colsRepeatedNode.getNodeValue(); colsRepeated = Integer.parseInt(colsRepeatedString); } else { // The cell is not repeated colsRepeated = 1; } // if there is no style we need to check to see if there is a default // cell style defined in the table-column's if (fmt.isDefault() && styleName.length() == 0) { int index = 1; for (Iterator<ColumnRowInfo> e = ColumnRowList.iterator(); e.hasNext(); ) { ColumnRowInfo cri = e.next(); if (cri.isColumn()) { if (colID >= index && colID < (index + cri.getRepeated())) { fmt = new Format(cri.getFormat()); } index += cri.getRepeated(); } } } if (tableValueTypeNode != null) { String cellType = tableValueTypeNode.getNodeValue(); if (cellType.equalsIgnoreCase(CELLTYPE_STRING)) { // has text:p tag fmt.setCategory(CELLTYPE_STRING); Node tableStringValueNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_STRING_VALUE); Debug.log(Debug.TRACE, "Cell Type String : " + tableStringValueNode); if (tableStringValueNode != null) { fmt.setValue(tableStringValueNode.getNodeValue()); } } else if (cellType.equalsIgnoreCase(CELLTYPE_FLOAT)) { // has table:value attribute // has text:p tag // Determine the number of decimal places StarCalc // is displaying for this floating point output. fmt.setCategory(CELLTYPE_FLOAT); fmt.setDecimalPlaces(getDecimalPlaces(node)); Node tableValueNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_VALUE); fmt.setValue(tableValueNode.getNodeValue()); } else if (cellType.equalsIgnoreCase(CELLTYPE_TIME)) { // has table:time-value attribute // has text:p tag - which is the value we convert fmt.setCategory(CELLTYPE_TIME); Node tableTimeNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_TIME_VALUE); fmt.setValue(tableTimeNode.getNodeValue()); } else if (cellType.equalsIgnoreCase(CELLTYPE_DATE)) { // has table:date-value attribute // has text:p tag - which is the value we convert fmt.setCategory(CELLTYPE_DATE); Node tableDateNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_DATE_VALUE); fmt.setValue(tableDateNode.getNodeValue()); } else if (cellType.equalsIgnoreCase(CELLTYPE_CURRENCY)) { // has table:currency // has table:value attribute // has text:p tag fmt.setCategory(CELLTYPE_CURRENCY); fmt.setDecimalPlaces(getDecimalPlaces(node)); Node tableValueNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_VALUE); fmt.setValue(tableValueNode.getNodeValue()); } else if (cellType.equalsIgnoreCase(CELLTYPE_BOOLEAN)) { // has table:boolean-value attribute // has text:p tag - which is the value we convert fmt.setCategory(CELLTYPE_BOOLEAN); Node tableBooleanNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_BOOLEAN_VALUE); fmt.setValue(tableBooleanNode.getNodeValue()); } else if (cellType.equalsIgnoreCase(CELLTYPE_PERCENT)) { // has table:value attribute // has text:p tag fmt.setCategory(CELLTYPE_PERCENT); fmt.setDecimalPlaces(getDecimalPlaces(node)); Node tableValueNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_VALUE); fmt.setValue(tableValueNode.getNodeValue()); } else { Debug.log(Debug.TRACE, "No defined value type" + cellType); // Should never get here } } Node tableFormulaNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_FORMULA); if (tableFormulaNode != null) { if (tableValueTypeNode == null) { // If there is no value-type Node we must assume string-value fmt.setCategory(CELLTYPE_STRING); Node tableStringValueNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_STRING_VALUE); fmt.setValue(tableStringValueNode.getNodeValue()); } String cellFormula = tableFormulaNode.getNodeValue(); addCell(cellFormula); } else { // Text node, Date node, or Time node Debug.log(Debug.INFO, "TextNode, DateNode, TimeNode or BooleanNode\n"); // This handles the case where we have style information but no content if (node.hasChildNodes()) { NodeList childList = node.getChildNodes(); int len = childList.getLength(); for (int i = 0; i < len; i++) { Node child = childList.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { String childName = child.getNodeName(); if (childName.equals(TAG_PARAGRAPH)) { traverseParagraph(child); } } } } else if (!fmt.isDefault()) { addCell(""); } } // Increase the column counter by the number of times the // last cell was repeated. colID += colsRepeated; // Re-initialize the number of columns repeated before processing // the next cell data. colsRepeated = 1; }
/** * This method traverses the <i>table:table-column</i> {@code Node}. * * <p>Not yet implemented. * * @param node A <i>table:table-column</i> {@code Node}. * @throws IOException If any I/O error occurs. */ protected void traverseTableColumn(Node node) throws IOException { Debug.log(Debug.TRACE, "traverseColumn() : "); NamedNodeMap cellAtt = node.getAttributes(); Node tableStyleNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_STYLE_NAME); Node tableNumColRepeatingNode = cellAtt.getNamedItem(ATTRIBUTE_TABLE_NUM_COLUMNS_REPEATED); Node tableDefaultCellStyle = cellAtt.getNamedItem(ATTRIBUTE_DEFAULT_CELL_STYLE); int repeatedColumns = 1; int columnWidth = 0; ColumnRowInfo col = new ColumnRowInfo(ColumnRowInfo.COLUMN); if (tableNumColRepeatingNode != null) { Debug.log( Debug.TRACE, "traverseColumn() repeated-cols : " + tableNumColRepeatingNode.getNodeValue()); repeatedColumns = Integer.parseInt(tableNumColRepeatingNode.getNodeValue()); col.setRepeated(repeatedColumns); } String cellStyleName = ""; if (tableDefaultCellStyle != null) { cellStyleName = tableDefaultCellStyle.getNodeValue(); Debug.log(Debug.TRACE, "traverseColumn() default-cell-style : " + cellStyleName); } CellStyle cellStyle = null; if (cellStyleName.equalsIgnoreCase("Default") || cellStyleName.length() == 0) { Debug.log(Debug.TRACE, "No default cell Style Attribute was found"); } else { cellStyle = (CellStyle) styleCat.lookup( cellStyleName, SxcConstants.TABLE_CELL_STYLE_FAMILY, null, CellStyle.class); } if (cellStyle != null) { Format defaultFmt = new Format(cellStyle.getFormat()); col.setFormat(defaultFmt); } String styleName = ""; if (tableStyleNode != null) { styleName = tableStyleNode.getNodeValue(); } if (styleName.equalsIgnoreCase("Default") || styleName.length() == 0) { Debug.log(Debug.TRACE, "No defined Style Attribute was found"); } else { ColumnStyle cStyle = (ColumnStyle) styleCat.lookup(styleName, SxcConstants.COLUMN_STYLE_FAMILY, null, ColumnStyle.class); columnWidth = cStyle != null ? cStyle.getColWidth() : 0; col.setSize(columnWidth); Debug.log(Debug.TRACE, "traverseColumn() Column Width : " + columnWidth); } ColumnRowList.add(col); }
/** Create a library of cell styles */ private static Map<String, CellStyle> createStyles(Workbook wb) { Map<String, CellStyle> styles = new HashMap<String, CellStyle>(); CellStyle style; Font titleFont = wb.createFont(); titleFont.setFontHeightInPoints((short) 18); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFont(titleFont); styles.put("title", style); Font monthFont = wb.createFont(); monthFont.setFontHeightInPoints((short) 11); monthFont.setColor(IndexedColors.WHITE.getIndex()); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFont(monthFont); style.setWrapText(true); styles.put("header", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setWrapText(true); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); styles.put("cell", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(wb.createDataFormat().getFormat("0.00")); styles.put("formula", style); style = wb.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setDataFormat(wb.createDataFormat().getFormat("0.00")); styles.put("formula_2", style); return styles; }
protected SCellStyle importCellStyle(CellStyle poiCellStyle, boolean inStyleTable) { SCellStyle cellStyle = null; // short idx = poiCellStyle.getIndex(); // ZSS-685 if ((cellStyle = importedStyle.get(poiCellStyle)) == null) { // ZSS-685 cellStyle = book.createCellStyle(inStyleTable); importedStyle.put(poiCellStyle, cellStyle); // ZSS-685 String dataFormat = poiCellStyle.getRawDataFormatString(); if (dataFormat == null) { // just in case dataFormat = SCellStyle.FORMAT_GENERAL; } if (!poiCellStyle.isBuiltinDataFormat()) { cellStyle.setDirectDataFormat(dataFormat); } else { cellStyle.setDataFormat(dataFormat); } cellStyle.setWrapText(poiCellStyle.getWrapText()); cellStyle.setLocked(poiCellStyle.getLocked()); cellStyle.setAlignment(PoiEnumConversion.toHorizontalAlignment(poiCellStyle.getAlignment())); cellStyle.setVerticalAlignment( PoiEnumConversion.toVerticalAlignment(poiCellStyle.getVerticalAlignment())); cellStyle.setRotation(poiCellStyle.getRotation()); // ZSS-918 cellStyle.setIndention(poiCellStyle.getIndention()); // ZSS-915 Color fgColor = poiCellStyle.getFillForegroundColorColor(); Color bgColor = poiCellStyle.getFillBackgroundColorColor(); // if (fgColor == null && bgColor != null) { //ZSS-797 // fgColor = bgColor; // } // ZSS-857: SOLID pattern: switch fillColor and backColor cellStyle.setFillPattern(PoiEnumConversion.toFillPattern(poiCellStyle.getFillPattern())); SColor fgSColor = book.createColor(BookHelper.colorToForegroundHTML(workbook, fgColor)); SColor bgSColor = book.createColor(BookHelper.colorToBackgroundHTML(workbook, bgColor)); if (cellStyle.getFillPattern() == FillPattern.SOLID) { SColor tmp = fgSColor; fgSColor = bgSColor; bgSColor = tmp; } cellStyle.setFillColor(fgSColor); cellStyle.setBackColor(bgSColor); // ZSS-780 cellStyle.setBorderLeft(PoiEnumConversion.toBorderType(poiCellStyle.getBorderLeft())); cellStyle.setBorderTop(PoiEnumConversion.toBorderType(poiCellStyle.getBorderTop())); cellStyle.setBorderRight(PoiEnumConversion.toBorderType(poiCellStyle.getBorderRight())); cellStyle.setBorderBottom(PoiEnumConversion.toBorderType(poiCellStyle.getBorderBottom())); cellStyle.setBorderLeftColor( book.createColor( BookHelper.colorToBorderHTML(workbook, poiCellStyle.getLeftBorderColorColor()))); cellStyle.setBorderTopColor( book.createColor( BookHelper.colorToBorderHTML(workbook, poiCellStyle.getTopBorderColorColor()))); cellStyle.setBorderRightColor( book.createColor( BookHelper.colorToBorderHTML(workbook, poiCellStyle.getRightBorderColorColor()))); cellStyle.setBorderBottomColor( book.createColor( BookHelper.colorToBorderHTML(workbook, poiCellStyle.getBottomBorderColorColor()))); cellStyle.setHidden(poiCellStyle.getHidden()); // same style always use same font cellStyle.setFont(importFont(poiCellStyle)); } return cellStyle; }