/** * 罫線スタイルの<b>CellStyle</b>を生成 1行のみ描画する * * @param workbook ワークブック * @param sheet シート * @param nRow 行 * @param nColumn 列 * @param isBold 太字フラグ * @param fontSize 文字サイズ * @param fontHeight 行高 */ public static void setCellStyleForLabel( XSSFWorkbook workbook, XSSFSheet sheet, int nRow, int nColumn, boolean isBold, short fontSize, float fontHeight) { assert sheet != null; // style設定 XSSFCellStyle style = workbook.createCellStyle(); XSSFFont font = workbook.createFont(); if (isBold) { font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); // 文字太字 } font.setFontHeightInPoints((short) fontSize); // 文字サイズ font.setFontName(DEFAULT_FONT_NAME); style.setFont(font); // 文字太字 と 文字サイズ style.setAlignment(CellStyle.ALIGN_GENERAL); // 水平方向の標準 style.setVerticalAlignment(CellStyle.VERTICAL_TOP); // 垂直方向の上詰め style.setWrapText(true); // 折り返して全体を表示する // セルに罫線を描画 XSSFRow row = getRowAnyway(sheet, nRow); XSSFCell cell = getCellAnyway(row, nColumn); cell.setCellStyle(style); row.setHeightInPoints(fontHeight); // 行高設定 }
/** * 创建标题,并设置字体、字号、加粗、颜色 * * @param workbook */ private void setHeadCellFont(XSSFWorkbook workbook, String title) { XSSFCellStyle style = workbook.createCellStyle(); XSSFRow row = (XSSFRow) workbook.getSheetAt(0).createRow(0); // 创建一个行对象 XSSFCell cell = row.createCell(0); // 创建单元格 XSSFFont font = workbook.createFont(); // 创建字体对象 font.setFontName(HSSFFont.FONT_ARIAL); // 字体 font.setFontHeightInPoints((short) 16); // 字号 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 加粗 style.setFont(font); style.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION); // 水平居中 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中 row.setHeightInPoints(23); // 设置行高23像素 cell.setCellStyle(style); // 应用样式对象 workbook .getSheetAt(0) .addMergedRegion(new CellRangeAddress(0, 0, 0, 16)); // 四个参数分别是:起始行,结束行,起始列,结束列 cell.setCellValue(title); // 写入头标题 }
private void renderCell( BandElement bandElement, String bandName, Object value, int gridRow, int sheetRow, int sheetColumn, int rowSpan, int colSpan, boolean image) { if (bandElement instanceof ReportBandElement) { colSpan = 1; } XSSFCellStyle cellStyle = buildBandElementStyle(bandElement, value, gridRow, sheetColumn, colSpan); // if we have a subreport on the current grid row we have to take care of the sheetColumn if (ReportLayout.HEADER_BAND_NAME.equals(bandName) && (gridRow == prevSubreportFirstRow) && (prevSubreportLastColumn != -1)) { sheetColumn = prevSubreportLastColumn - prevSubreportFirstColumn - 1 + sheetColumn; } XSSFCell c = xlsRow.createCell(sheetColumn); if (image) { if ((value == null) || "".equals(value)) { c.setCellType(XSSFCell.CELL_TYPE_STRING); c.setCellValue(wb.getCreationHelper().createRichTextString(IMAGE_NOT_FOUND)); } else { try { ImageBandElement ibe = (ImageBandElement) bandElement; byte[] imageBytes = getImage((String) value, ibe.getWidth(), ibe.getHeight()); XSSFClientAnchor anchor = new XSSFClientAnchor( 0, 0, 0, 0, (short) sheetColumn, sheetRow, (short) (sheetColumn + colSpan), (sheetRow + rowSpan)); int index = wb.addPicture(imageBytes, XSSFWorkbook.PICTURE_TYPE_JPEG); // image is created over the cells, so if it's height is bigger we set the row height short height = xlsRow.getHeight(); int realImageHeight = getRealImageSize((String) value)[1]; if (ibe.isScaled()) { realImageHeight = ibe.getHeight(); } short imageHeight = (short) (realImageHeight * POINTS_FOR_PIXEL / 2.5); boolean doResize = false; if (imageHeight > height) { xlsRow.setHeight(imageHeight); } else { doResize = true; } Picture picture = patriarch.createPicture(anchor, index); if (doResize) { picture.resize(); } anchor.setAnchorType(2); } catch (Exception ex) { c.setCellType(XSSFCell.CELL_TYPE_STRING); c.setCellValue(wb.getCreationHelper().createRichTextString(IMAGE_NOT_LOADED)); } } if (cellStyle != null) { c.setCellStyle(cellStyle); } } else { if (bandElement instanceof HyperlinkBandElement) { Hyperlink hyp = ((HyperlinkBandElement) bandElement).getHyperlink(); XSSFHyperlink link = wb.getCreationHelper().createHyperlink(XSSFHyperlink.LINK_URL); link.setAddress(hyp.getUrl()); c.setHyperlink(link); c.setCellValue(wb.getCreationHelper().createRichTextString(hyp.getText())); c.setCellType(XSSFCell.CELL_TYPE_STRING); } else if (bandElement instanceof ReportBandElement) { Report report = ((ReportBandElement) bandElement).getReport(); ExporterBean eb = null; try { eb = getSubreportExporterBean(report, true); XlsxExporter subExporter = new XlsxExporter(eb, cellStyle); subExporter.export(); XSSFSheet subreportSheet = subExporter.getSubreportSheet(); if (ReportLayout.HEADER_BAND_NAME.equals(bandName) && (gridRow == prevSubreportFirstRow)) { // other subreports on the same header line after the first sheetColumn = prevSubreportLastColumn; sheetRow -= addedPageRows; pageRow -= addedPageRows; addedPageRows = 0; } else { addedPageRows = subreportSheet.getLastRowNum(); pageRow += addedPageRows; // if subreport is not on the first column we merge all cells in the columns before, // between the rows subreport occupies if (sheetColumn > 0) { for (int i = 0; i <= sheetColumn - 1; i++) { CellRangeAddress cra = new CellRangeAddress(sheetRow, pageRow, i, i); regions.add(new XlsxRegion(cra, null)); } } } int cols = XlsxUtil.copyToSheet(xlsSheet, sheetRow, sheetColumn, subreportSheet); addRegions(xlsSheet, subExporter.getSubreportRegions(), wb); if (ReportLayout.HEADER_BAND_NAME.equals(bandName)) { prevSubreportFirstRow = gridRow; prevSubreportFirstColumn = sheetColumn; prevSubreportLastColumn = sheetColumn + cols; } } catch (Exception e) { e.printStackTrace(); } finally { if ((eb != null) && (eb.getResult() != null)) { eb.getResult().close(); } } } else if (bandElement instanceof ImageColumnBandElement) { try { ImageColumnBandElement icbe = (ImageColumnBandElement) bandElement; String v = StringUtil.getValueAsString(value, null); if (StringUtil.BLOB.equals(v)) { c.setCellType(XSSFCell.CELL_TYPE_STRING); c.setCellValue(wb.getCreationHelper().createRichTextString(StringUtil.BLOB)); } else { byte[] imageD = StringUtil.decodeImage(v); byte[] imageBytes = getImage(imageD, icbe.getWidth(), icbe.getHeight()); XSSFClientAnchor anchor = new XSSFClientAnchor( 0, 0, 0, 0, (short) sheetColumn, sheetRow, (short) (sheetColumn + colSpan), (sheetRow + rowSpan)); int index = wb.addPicture(imageBytes, XSSFWorkbook.PICTURE_TYPE_JPEG); // image is created over the cells, so if it's height is bigger we set the row height short height = xlsRow.getHeight(); int realImageHeight = getRealImageSize(imageBytes)[1]; if (icbe.isScaled()) { realImageHeight = icbe.getHeight(); } short imageHeight = (short) (realImageHeight * POINTS_FOR_PIXEL / 2.5); if (imageHeight > height) { xlsRow.setHeight(imageHeight); } Picture picture = patriarch.createPicture(anchor, index); picture.resize(); anchor.setAnchorType(2); } } catch (Exception e) { e.printStackTrace(); c.setCellType(XSSFCell.CELL_TYPE_STRING); c.setCellValue(wb.getCreationHelper().createRichTextString(IMAGE_NOT_LOADED)); } } else { if (value == null) { c.setCellType(XSSFCell.CELL_TYPE_STRING); c.setCellValue(wb.getCreationHelper().createRichTextString("")); } else if (value instanceof Number) { c.setCellType(XSSFCell.CELL_TYPE_NUMERIC); c.setCellValue(((Number) value).doubleValue()); } else { String pattern = null; if (bandElement instanceof FieldBandElement) { FieldBandElement fbe = (FieldBandElement) bandElement; pattern = fbe.getPattern(); } if ((value instanceof java.sql.Date) || (value instanceof java.sql.Timestamp)) { Date date; if (value instanceof java.sql.Date) { date = new Date(((java.sql.Date) value).getTime()); } else { date = (java.sql.Timestamp) value; } if (cellStyle != null) { if (pattern == null) { // use default pattern if none selected Locale locale = Locale.getDefault(); pattern = ((SimpleDateFormat) DateFormat.getDateInstance(SimpleDateFormat.MEDIUM, locale)) .toPattern(); } else { pattern = StringUtil.getI18nString(pattern, getReportLanguage()); } cellStyle.setDataFormat(wb.createDataFormat().getFormat(pattern)); } c.setCellValue(date); } else { c.setCellType(XSSFCell.CELL_TYPE_STRING); String text = StringUtil.getValueAsString(value, pattern); if ((bandElement != null) && bandElement.isWrapText()) { // try to interpret new line characters // \\n is used here to be possible to add in designer grid cell with \n if (text.contains("\\n") || text.contains("\n") || text.contains("\r") || text.contains("\r\n")) { String crLf = Character.toString((char) 13) + Character.toString((char) 10); int lines = countLines(text); if (text.contains("\r\n")) { text = text.replaceAll("\r\n", crLf); } else { text = text.replaceAll("(\n)|(\r)|(\\\\n)", crLf); } c.setCellValue(text); cellStyle.setWrapText(true); xlsRow.setHeightInPoints(lines * (cellStyle.getFont().getFontHeightInPoints() + 3)); } else { c.setCellValue(wb.getCreationHelper().createRichTextString(text)); } } else { c.setCellValue(wb.getCreationHelper().createRichTextString(text)); } } } } if (cellStyle != null) { if (bandElement != null) { cellStyle.setRotation(bandElement.getTextRotation()); } if (!(bandElement instanceof ReportBandElement)) { c.setCellStyle(cellStyle); } } if ((rowSpan > 1) || (colSpan > 1)) { CellRangeAddress cra = new CellRangeAddress( sheetRow, sheetRow + rowSpan - 1, sheetColumn, sheetColumn + colSpan - 1); Border beBorder = bandElement.getBorder(); if (hasRowRenderConditions(bandElement, gridRow, value)) { // for row render conditions we must keep the row border beBorder = border; } regions.add(new XlsxRegion(cra, beBorder)); } } }
@Override public Workbook writeWorkbook( Workbook workbook, String sheetTitle, List<List<String>> tableDataList, int headerNum) { if (workbook == null) workbook = new XSSFWorkbook(); int exportRecordNum = tableDataList.size(); // 导出的总记录数 int tableStartRowNum = headerNum > 0 ? headerNum : 0; // 表体数据开始行数 int sheetNum = exportRecordNum / (CommonConst.EXCEL_MAX_EXPORT_NUM - headerNum) + 1; // 工作表的页数 List<XSSFSheet> sheetList = new ArrayList<XSSFSheet>(); if (StringUtils.isEmpty(sheetTitle)) sheetTitle = "sheet"; for (int i = 0; i < sheetNum; i++) { // 在Excel工作簿中建一工作表 String sTitle = sheetTitle + (i + 1); XSSFSheet sheet = (XSSFSheet) workbook.createSheet(sTitle); sheet.setSelected(true); // 设置工作薄为选中 sheet.setAutobreaks(true); sheet.setPrintGridlines(true); sheetList.add(sheet); } /** ***********************输出表头********************************* */ if (headerNum > 0) { for (XSSFSheet sheet : sheetList) { XSSFRow headRow = sheet.createRow(0); headRow.setHeightInPoints(20); for (int i = 0; i < headerNum; i++) { List<String> headerRowDataList = tableDataList.get(i); for (int j = 0; j < headerRowDataList.size(); j++) { XSSFCellStyle cellStyle = (XSSFCellStyle) createDefHeaderCellStyle(workbook); // 默认表头样式 createCell(headRow, j, headerRowDataList.get(j), cellStyle); } } // 固定表头 sheet.createFreezePane(0, 1); } } /** *********************输出表体内容************************* */ // 设置列样式 XSSFCellStyle columnStyle = (XSSFCellStyle) workbook.createCellStyle(); columnStyle.setFillBackgroundColor(HSSFColor.GREEN.index); columnStyle.setWrapText(true); if (tableDataList.size() > (tableStartRowNum + 1)) { for (int i = tableStartRowNum; i < exportRecordNum; i++) { List<String> rowDataList = tableDataList.get(i); XSSFRow row = null; int currentSheet = i / CommonConst.EXCEL_MAX_EXPORT_NUM; // 当前工作表的页数 XSSFSheet sheet = sheetList.get(currentSheet); int rowIndex = i - CommonConst.EXCEL_MAX_EXPORT_NUM * currentSheet; row = sheet.createRow(rowIndex); for (int colIndex = 0, colLength = rowDataList.size(); colIndex < colLength; colIndex++) { createCell(row, colIndex, rowDataList.get(colIndex)); } } } // 调整列的宽度(取第一列为基准) for (XSSFSheet sheet : sheetList) { for (int i = 0; i < tableDataList.get(0).size(); i++) { sheet.autoSizeColumn((short) i); sheet.setColumnWidth((short) i, (short) (sheet.getColumnWidth((short) i) + 1000)); } } return workbook; }