Exemplo n.º 1
5
 /**
  * 初始化函数
  *
  * @param title 表格标题,传“空值”,表示无标题
  * @param headerList 表头列表
  */
 private void initialize(String title, List<String> headerList) {
   this.wb = new SXSSFWorkbook(500);
   this.sheet = wb.createSheet("Export");
   this.styles = createStyles(wb);
   // Create title
   if (StringUtils.isNotBlank(title)) {
     Row titleRow = sheet.createRow(rownum++);
     titleRow.setHeightInPoints(30);
     Cell titleCell = titleRow.createCell(0);
     titleCell.setCellStyle(styles.get("title"));
     titleCell.setCellValue(title);
     sheet.addMergedRegion(
         new CellRangeAddress(
             titleRow.getRowNum(),
             titleRow.getRowNum(),
             titleRow.getRowNum(),
             headerList.size() - 1));
   }
   // Create header
   if (headerList == null) {
     throw new RuntimeException("headerList not null!");
   }
   Row headerRow = sheet.createRow(rownum++);
   headerRow.setHeightInPoints(16);
   for (int i = 0; i < headerList.size(); i++) {
     Cell cell = headerRow.createCell(i);
     cell.setCellStyle(styles.get("header"));
     String[] ss = StringUtils.split(headerList.get(i), "**", 2);
     if (ss.length == 2) {
       cell.setCellValue(ss[0]);
       Comment comment =
           this.sheet
               .createDrawingPatriarch()
               .createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
       comment.setString(new XSSFRichTextString(ss[1]));
       cell.setCellComment(comment);
     } else {
       cell.setCellValue(headerList.get(i));
     }
     sheet.autoSizeColumn(i);
   }
   for (int i = 0; i < headerList.size(); i++) {
     int colWidth = sheet.getColumnWidth(i) * 2;
     sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
   }
   log.debug("Initialize success.");
 }
  private void headerProcess(Sheet tempSheet, Sheet newSheet, Date cycleFrom, Date cycleTo)
      throws Exception {
    Cell tCell = tempSheet.getRow(0).getCell(0, Row.CREATE_NULL_AS_BLANK);
    Cell nCell = newSheet.createRow(0).createCell(0, tCell.getCellType());
    nCell.setCellValue(tCell.getStringCellValue().replaceAll(PARAM_COMPANY, FWD_COMP_NAME));
    nCell.setCellStyle(tCell.getCellStyle());

    tCell = tempSheet.getRow(1).getCell(0, Row.CREATE_NULL_AS_BLANK);
    nCell = newSheet.createRow(1).createCell(0, tCell.getCellType());
    nCell.setCellValue(
        tCell
            .getStringCellValue()
            .replaceAll(PARAM_ABBR_NAME, "ADAMS-TVD")
            .replaceAll(
                PARAM_CYCLE_FROM, DateUtil.convDateToString(DISPLAY_DATE_PATTERN, cycleFrom))
            .replaceAll(PARAM_CYCLE_TO, DateUtil.convDateToString(DISPLAY_DATE_PATTERN, cycleTo)));
    nCell.setCellStyle(tCell.getCellStyle());

    Row tempRow = tempSheet.getRow(4);
    Row newRow = newSheet.createRow(4);

    for (int c = 0; c < tempRow.getLastCellNum(); c++) {
      tCell = tempRow.getCell(c, Row.CREATE_NULL_AS_BLANK);
      nCell = newRow.createCell(c, tCell.getCellType());
      nCell.setCellValue(tCell.getStringCellValue());
      nCell.setCellStyle(tCell.getCellStyle());
    }

    for (int i = 0; i < tempSheet.getNumMergedRegions(); i++) {
      CellRangeAddress mergedRegion = tempSheet.getMergedRegion(i);
      newSheet.addMergedRegion(mergedRegion);
    }
  }
Exemplo n.º 3
0
 public static void copySheet(Sheet sheet, Sheet newSheet) {
   int maxCol = 0;
   for (int row = 0; row <= sheet.getLastRowNum(); row++) {
     Row oldRow = sheet.getRow(row);
     if (oldRow == null) continue;
     Row newRow = newSheet.getRow(row);
     if (newRow == null) newRow = newSheet.createRow(row);
     if (oldRow.getHeight() >= 0) newRow.setHeight(oldRow.getHeight());
     maxCol = (maxCol >= oldRow.getLastCellNum() - 1 ? maxCol : oldRow.getLastCellNum() - 1);
     for (int col = 0; col < oldRow.getLastCellNum(); col++) {
       Cell oldCell = oldRow.getCell(col);
       if (oldCell == null) continue;
       Cell newCell = newRow.getCell(col);
       if (newCell == null) newCell = newRow.createCell(col);
       copyCell(oldCell, newCell, true);
     }
   }
   for (int col = 0; col <= maxCol; col++) {
     if (sheet.getColumnWidth(col) >= 0) newSheet.setColumnWidth(col, sheet.getColumnWidth(col));
   }
   for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
     CellRangeAddress cra = sheet.getMergedRegion(i);
     newSheet.addMergedRegion(cra);
   }
 }
  // =================================================================================================================================
  private int exportFrontEquipListReport_header(
      List<FrontEquipListReport_subtype> subtypes, int rownum, XSSFWorkbook wb, Sheet sheet) {
    CellStyle style = getHeaderStyle(wb, (short) 11);
    CellStyle style2 = getHeaderStyle(wb, (short) 10);

    // 第一行列标题
    Row row_subtype = sheet.createRow(rownum++);
    Cell cell_subtype_0 = row_subtype.createCell(0);
    cell_subtype_0.setCellValue("");
    cell_subtype_0.setCellStyle(style);
    sheet.setColumnWidth(0, 700);
    Cell cell_subtype_1 = row_subtype.createCell(1);
    cell_subtype_1.setCellValue("");
    cell_subtype_1.setCellStyle(style);
    sheet.setColumnWidth(1, 1800);
    Cell cell_subtype_2 = row_subtype.createCell(2);
    cell_subtype_2.setCellValue("");
    cell_subtype_2.setCellStyle(style);
    sheet.setColumnWidth(2, 4800);

    // 第二行列标题
    Row row_prod = sheet.createRow(rownum++);
    Cell cell_prod_0 = row_prod.createCell(0);
    cell_prod_0.setCellValue("序号");
    cell_prod_0.setCellStyle(style2);
    Cell cell_prod_1 = row_prod.createCell(1);
    cell_prod_1.setCellValue("点位编号");
    cell_prod_1.setCellStyle(style2);
    Cell cell_prod_2 = row_prod.createCell(2);
    cell_prod_2.setCellValue("点位名称");
    cell_prod_2.setCellStyle(style2);

    int cell_num = 3;
    for (FrontEquipListReport_subtype subtype : subtypes) {
      int start_cell_num = cell_num;
      Cell cell_subtype = row_subtype.createCell(cell_num);
      cell_subtype.setCellValue(subtype.getSubtype_name());
      cell_subtype.setCellStyle(style);

      for (FrontEquipListReport_prod prod : subtype.getProds()) {
        if (start_cell_num != cell_num) {
          cell_subtype = row_subtype.createCell(cell_num);
          cell_subtype.setCellStyle(style);
        }

        Cell cell_prod = row_prod.createCell(cell_num);
        cell_prod.setCellValue(prod.getProd_name() + "(" + prod.getProd_style() + ")");
        cell_prod.setCellStyle(style2);
        cell_num++;
      }
      // 对子类型进行横向的单元格合并
      sheet.addMergedRegion(
          new CellRangeAddress(1, (short) 1, start_cell_num, (short) cell_num - 1));
    }

    return rownum;
  }
  private void addSumBottom() {
    for (int i = 0; i < book.getNumberOfSheets(); i++) {
      Sheet sheet = book.getSheetAt(i);

      Row row = sheet.createRow(sheet.getLastRowNum() + 1);
      row.setHeight((short) (ROW_HEIGHT + 100));

      for (int j = 0; j < 1000000; j++) {
        if (StringUtils.isBlank(CellUtils.getStringValue(sheet.getRow(0).getCell(j)))
            && StringUtils.isBlank(CellUtils.getStringValue(sheet.getRow(2).getCell(j)))) {
          break;
        }
        Cell cell = row.createCell(j);
        cell.setCellStyle(Style.get(book).SUM);
        if (j == 0) {
          cell.setCellValue("合计");
        } else {
          cell.setCellValue(0);
        }

        if (j >= 7) {
          cell.setCellType(Cell.CELL_TYPE_FORMULA);
          cell.setCellFormula(
              String.format(
                  "SUM(%s%s:%s%s)",
                  CellUtils.convertToABC(j + 1),
                  5,
                  CellUtils.convertToABC(j + 1),
                  sheet.getLastRowNum()));
        }
      }
      sheet.addMergedRegion(
          new CellRangeAddress(sheet.getLastRowNum(), sheet.getLastRowNum(), 0, 6));
    }

    for (int i = 0; i < book.getNumberOfSheets(); i++) {
      Sheet sheet = book.getSheetAt(i);
      for (int j = 4; j <= sheet.getLastRowNum(); j++) {
        Row row = sheet.getRow(j);
        for (int k = 0; k <= row.getLastCellNum(); k++) {
          Cell cell = row.getCell(k);
          if (cell == null) {
            continue;
          }

          if ("数量".equals(CellUtils.getStringValue(sheet.getRow(2).getCell(k)))) {
            cell.setCellStyle(Style.get(book).SUM);
          }
        }
      }
    }
  }
  /**
   * Builds the rows' headers recursively with this order: |-----|-----|-----| | | | 3 | | | |-----|
   * | | 2 | 4 | | | |-----| | 1 | | 5 | | |-----|-----| | | | 7 | | | 6 |-----| | | | 8 |
   * |-----|-----|-----| | | | 11 | | 9 | 10 |-----| | | | 12 | |-----|-----|-----|
   *
   * @param sheet The sheet of the XLS file
   * @param siblings The siblings nodes of the headers structure
   * @param rowNum The row number where the first sibling must be inserted
   * @param columnNum The column number where the siblings must be inserted
   * @param createHelper The file creation helper
   * @throws JSONException
   */
  protected void buildRowsHeaders(
      Sheet sheet,
      CrossTab cs,
      List<Node> siblings,
      int rowNum,
      int columnNum,
      CreationHelper createHelper,
      Locale locale,
      CellStyle cellStyle)
      throws JSONException {
    int rowsCounter = rowNum;

    for (int i = 0; i < siblings.size(); i++) {
      Node aNode = siblings.get(i);
      List<Node> childs = aNode.getChilds();
      Row row = sheet.getRow(rowsCounter);
      Cell cell = row.createCell(columnNum);
      String text = (String) aNode.getDescription();

      if (cs.isMeasureOnRow() && (childs == null || childs.size() <= 0)) {
        // apply the measure scale factor
        text = MeasureScaleFactorOption.getScaledName(text, cs.getMeasureScaleFactor(text), locale);
      }
      cell.setCellValue(createHelper.createRichTextString(text));
      cell.setCellType(this.getCellTypeString());

      cell.setCellStyle(cellStyle);

      int descendants = aNode.getLeafsNumber();
      if (descendants > 1) {
        sheet.addMergedRegion(
            new CellRangeAddress(
                rowsCounter, // first row (0-based)
                rowsCounter + descendants - 1, // last row  (0-based)
                columnNum, // first column (0-based)
                columnNum // last column  (0-based)
                ));
      }

      if (childs != null && childs.size() > 0) {
        buildRowsHeaders(
            sheet, cs, childs, rowsCounter, columnNum + 1, createHelper, locale, cellStyle);
      }
      int increment = descendants > 1 ? descendants : 1;
      rowsCounter = rowsCounter + increment;
    }
  }
Exemplo n.º 7
0
 public static void copyBlock(
     Sheet sheet,
     int startRow,
     int startCol,
     int endRow,
     int endCol,
     boolean copyStyle,
     int rowOffset,
     int colOffset,
     List<CellRangeAddress> mergedRegions) {
   for (int row = startRow; row <= endRow; row++) {
     Row oldRow = sheet.getRow(row);
     if (oldRow == null) continue;
     Row newRow = sheet.getRow(row + rowOffset);
     if (newRow == null) newRow = sheet.createRow(row + rowOffset);
     if (oldRow.getHeight() >= 0) newRow.setHeight(oldRow.getHeight());
     if (logger.isDebugEnabled()) {
       logger.debug("copy row {} to {}", row, row + rowOffset);
       logger.debug("Set row height :{}", newRow.getHeightInPoints());
     }
     for (int col = startCol; col <= endCol; col++) {
       Cell oldCell = oldRow.getCell(col);
       if (oldCell == null) continue;
       Cell newCell = newRow.getCell(col + colOffset);
       if (newCell == null) newCell = newRow.createCell(col + colOffset);
       copyCell(oldCell, newCell, copyStyle, rowOffset, colOffset);
     }
   }
   for (int col = startCol; col <= endCol; col++) {
     if (sheet.getColumnWidth(col) >= 0)
       sheet.setColumnWidth(col + colOffset, sheet.getColumnWidth(col));
   }
   if (mergedRegions != null) {
     for (CellRangeAddress cra : mergedRegions) {
       CellRangeAddress craNew =
           new CellRangeAddress(
               cra.getFirstRow() + rowOffset,
               cra.getLastRow() + rowOffset,
               cra.getFirstColumn() + colOffset,
               cra.getLastColumn() + colOffset);
       sheet.addMergedRegion(craNew);
     }
   }
 }
Exemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    Workbook wb;

    if (args.length > 0 && args[0].equals("-xls")) wb = new HSSFWorkbook();
    else wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("Timesheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    // title row
    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Weekly Timesheet");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$L$1"));

    // header row
    Row headerRow = sheet.createRow(1);
    headerRow.setHeightInPoints(40);
    Cell headerCell;
    for (int i = 0; i < titles.length; i++) {
      headerCell = headerRow.createCell(i);
      headerCell.setCellValue(titles[i]);
      headerCell.setCellStyle(styles.get("header"));
    }

    int rownum = 2;
    for (int i = 0; i < 10; i++) {
      Row row = sheet.createRow(rownum++);
      for (int j = 0; j < titles.length; j++) {
        Cell cell = row.createCell(j);
        if (j == 9) {
          // the 10th cell contains sum over week days, e.g. SUM(C3:I3)
          String ref = "C" + rownum + ":I" + rownum;
          cell.setCellFormula("SUM(" + ref + ")");
          cell.setCellStyle(styles.get("formula"));
        } else if (j == 11) {
          cell.setCellFormula("J" + rownum + "-K" + rownum);
          cell.setCellStyle(styles.get("formula"));
        } else {
          cell.setCellStyle(styles.get("cell"));
        }
      }
    }

    // row with totals below
    Row sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(35);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellValue("Total Hrs:");
    cell.setCellStyle(styles.get("formula"));

    for (int j = 2; j < 12; j++) {
      cell = sumRow.createCell(j);
      String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
      cell.setCellFormula("SUM(" + ref + ")");
      if (j >= 9) cell.setCellStyle(styles.get("formula_2"));
      else cell.setCellStyle(styles.get("formula"));
    }
    rownum++;
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Regular Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("L13");
    cell.setCellStyle(styles.get("formula_2"));
    sumRow = sheet.createRow(rownum++);
    sumRow.setHeightInPoints(25);
    cell = sumRow.createCell(0);
    cell.setCellValue("Total Overtime Hours");
    cell.setCellStyle(styles.get("formula"));
    cell = sumRow.createCell(1);
    cell.setCellFormula("K13");
    cell.setCellStyle(styles.get("formula_2"));

    // set sample data
    for (int i = 0; i < sample_data.length; i++) {
      Row row = sheet.getRow(2 + i);
      for (int j = 0; j < sample_data[i].length; j++) {
        if (sample_data[i][j] == null) continue;

        if (sample_data[i][j] instanceof String) {
          row.getCell(j).setCellValue((String) sample_data[i][j]);
        } else {
          row.getCell(j).setCellValue((Double) sample_data[i][j]);
        }
      }
    }

    // finally set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 30 * 256); // 30 characters wide
    for (int i = 2; i < 9; i++) {
      sheet.setColumnWidth(i, 6 * 256); // 6 characters wide
    }
    sheet.setColumnWidth(10, 10 * 256); // 10 characters wide

    // Write the output to a file
    String file = "timesheet.xls";
    if (wb instanceof XSSFWorkbook) file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
  }
  @Test
  public void generateExcelPoiReport() throws IOException {

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Accounts");

    int rowNum = 1;
    Row row = sheet.createRow(rowNum++);

    Font font = wb.createFont();
    font.setFontHeightInPoints((short) 24);
    font.setFontName(FONT_TYPE);
    font.setColor(FONT_COLOR_TITLE);

    /** * Header **** */
    CellStyle style = wb.createCellStyle();
    style.setFont(font);
    style.setAlignment(CellStyle.ALIGN_CENTER);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    style.setFillForegroundColor(BACKGROUND_COLOR);

    Cell cell = row.createCell((short) 1);
    cell.setCellValue("Account Report per Beneficiary");
    cell.setCellStyle(style);
    sheet.addMergedRegion(
        new CellRangeAddress(
            1, // first row (0-based)
            2, // last row  (0-based)
            1, // first column (0-based)
            16 // last column  (0-based)
            ));

    /** * Body **** */
    font = wb.createFont();
    font.setFontHeightInPoints((short) 12);
    font.setFontName(FONT_TYPE);
    font.setColor(FONT_COLOR);

    style = wb.createCellStyle();
    style.setFont(font);

    rowNum = rowNum + 3;
    List<Account> accounts = accountManager.getAllAccounts();
    for (Account account : accounts) {

      row = sheet.createRow(rowNum++);

      cell = row.createCell((short) 1);
      cell.setCellStyle(style);
      cell.setCellValue(account.getName());

      cell = row.createCell((short) 2);
      cell.setCellValue(account.getNumber());
      cell.setCellStyle(style);

      cell = row.createCell((short) 3);
      cell.setCellValue(account.getEntityId());
      cell.setCellStyle(style);
    }

    sheet.autoSizeColumn(1);
    sheet.autoSizeColumn(2);
    sheet.autoSizeColumn(3);

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("C:/Temp/workbook.xls");
    wb.write(fileOut);
    fileOut.close();
  }
  // Define A method for Creating Excel File
  public String createExcel(
      String titleString,
      String sheetString,
      String subTitleString,
      List data,
      String[] headerTitles,
      String titleKey,
      String filePath) {

    String file = null;
    Workbook wb;
    int col = 0;
    try {
      // check Header Title
      if (headerTitles != null && headerTitles.length > 0) col = headerTitles.length;

      wb = (Workbook) new HSSFWorkbook();
      // Hear we are getting whole property
      List<ConfigurationUtilBean> titleMap = new CustomerCommonPropertyMap().getTitles(titleKey);
      Map<String, CellStyle> styles = createStyles(wb);
      Sheet sheet = wb.createSheet(sheetString);
      PrintSetup printSetup = sheet.getPrintSetup();
      printSetup.setLandscape(true);
      sheet.setFitToPage(true);
      sheet.setHorizontallyCenter(true);

      Header header = sheet.getHeader();
      header.setCenter("Center Header");
      header.setLeft("Left Header");
      header.setRight("Right Footer");
      Footer footer = sheet.getFooter();
      footer.setCenter("center footer");
      footer.setLeft("left footer");
      footer.setRight("right footer");

      // Title Row....
      Row titleRow = sheet.createRow(0);
      titleRow.setHeightInPoints(20);
      Cell titleCell = titleRow.createCell(0);
      titleCell.setCellValue(titleString);
      titleCell.setCellStyle(styles.get("title"));
      sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col - 1));

      // Sub Title Row.....
      // System.out.println("Sub Title String >>>>>>"+subTitleString);
      Row headerRow = null;
      if (subTitleString != "") {
        Row subTitleRow = sheet.createRow(1);
        subTitleRow.setHeightInPoints(18);
        Cell subTitleCell = subTitleRow.createCell(0);
        subTitleCell.setCellValue(subTitleString);
        subTitleCell.setCellStyle(styles.get("subTitle"));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, col - 1));
        headerRow = sheet.createRow(2);
        headerRow.setHeightInPoints(15);
        //
      } else {
        headerRow = sheet.createRow(1);
        headerRow.setHeightInPoints(15);
      }
      Cell headerCell = null;
      if (headerTitles != null) {
        for (ConfigurationUtilBean cell : titleMap) {
          int titleIndex = 0;
          for (int i = 0; i < headerTitles.length; i++) {
            if (cell.getKey().equalsIgnoreCase(headerTitles[titleIndex].trim())) {
              headerCell = headerRow.createCell(titleIndex);
              headerCell.setCellValue(cell.getValue());
              headerCell.setCellStyle(styles.get("header"));
            }
            titleIndex++;
          }
        }
      }
      Row dataRow = null;
      Cell dataCell = null;

      int rowIndex = 2;
      /* List Iteration text */
      try {
        if (data != null && data.size() > 0) {
          for (Iterator it = data.iterator(); it.hasNext(); ) {
            Object[] obdata = (Object[]) it.next();
            dataRow = sheet.createRow(rowIndex);
            for (int cellIndex = 0; cellIndex < headerTitles.length; cellIndex++) {
              dataCell = dataRow.createCell(cellIndex);

              if (obdata[cellIndex] != null && !obdata[cellIndex].toString().equalsIgnoreCase("")) {

                dataCell.setCellValue(obdata[cellIndex].toString());
              } else {
                dataCell.setCellValue("NA");
              }
            }

            rowIndex++;
          }
        }
      } catch (Exception e) {
        // TODO: handle exception
      }

      for (int titleIndex = 0; titleIndex < headerTitles.length; titleIndex++)
        sheet.autoSizeColumn(titleIndex); // adjust width of the column

      file =
          filePath
              + File.separator
              + "OpportunityReportDetail_"
              + DateUtil.getCurrentDateIndianFormat()
              + (DateUtil.getCurrentTimeHourMin()).replaceAll(":", "-")
              + ".xls";

      if (wb instanceof XSSFWorkbook) file += "x";
      FileOutputStream out = new FileOutputStream(file);
      wb.write(out);
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {

    }
    return file;
  }
  // Define A method for Creating Excel File
  public String createExcelformate(
      String titleString,
      String sheetString,
      String[] headerTitles,
      String titleKey,
      String filePath) {

    String file = null;
    Workbook wb;
    int col = 0;
    try {
      // check Header Title
      if (headerTitles != null && headerTitles.length > 0) col = headerTitles.length;

      wb = (Workbook) new HSSFWorkbook();
      // Hear we are getting whole property
      List<ConfigurationUtilBean> titleMap = new CustomerCommonPropertyMap().getTitles(titleKey);
      Map<String, CellStyle> styles = createStyles(wb);
      Sheet sheet = wb.createSheet(sheetString);
      PrintSetup printSetup = sheet.getPrintSetup();
      printSetup.setLandscape(true);
      sheet.setFitToPage(true);
      sheet.setHorizontallyCenter(true);

      Header header = sheet.getHeader();
      header.setCenter("Center Header");
      header.setLeft("Left Header");
      header.setRight("Right Footer");
      Footer footer = sheet.getFooter();
      footer.setCenter("center footer");
      footer.setLeft("left footer");
      footer.setRight("right footer");

      // Title Row....
      Row titleRow = sheet.createRow(0);
      titleRow.setHeightInPoints(20);
      Cell titleCell = titleRow.createCell(0);
      titleCell.setCellValue(titleString);
      titleCell.setCellStyle(styles.get("title"));
      sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, col - 1));

      //
      Row headerRow = sheet.createRow(1);
      headerRow.setHeightInPoints(15);
      Cell headerCell = null;
      if (headerTitles != null) {
        for (ConfigurationUtilBean cell : titleMap) {
          int titleIndex = 0;
          for (int i = 0; i < headerTitles.length; i++) {
            if (cell.getKey().equalsIgnoreCase(headerTitles[titleIndex].trim())) {
              headerCell = headerRow.createCell(titleIndex);
              headerCell.setCellValue(cell.getValue());
              headerCell.setCellStyle(styles.get("header"));
            }
            titleIndex++;
          }
        }
      }

      for (int titleIndex = 0; titleIndex < headerTitles.length; titleIndex++)
        sheet.autoSizeColumn(titleIndex); // adjust width of the column

      file =
          filePath
              + File.separator
              + "ContactReport"
              + DateUtil.getCurrentDateIndianFormat()
              + (DateUtil.getCurrentTime()).replaceAll(":", "-")
              + ".xls";

      if (wb instanceof XSSFWorkbook) file += "x";
      FileOutputStream out = new FileOutputStream(file);
      wb.write(out);
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {

    }
    return file;
  }
  /**
   * 资产明细表
   *
   * @param response
   * @param customer_2
   * @param customer_0or1
   * @throws IOException
   */
  @RequestMapping("/report/frontequip/exportFrontEquipListReport_assetclean.do")
  public void exportFrontEquipListReport_assetclean(
      HttpServletResponse response, String customer_2, String customer_0or1) throws IOException {

    String customer_2_name = customerService.get(customer_2).getName();
    String customer_0or1_name = customerService.get(customer_0or1).getName();
    List<FrontEquipListReport> list =
        frontEquipReportRepository.queryFrontEquipListReport(customer_2, customer_0or1);

    List<FrontEquipListReport_subtype> list_subtype_prod =
        frontEquipReportRepository.queryFrontEquipListReport_header(customer_2, customer_0or1);

    XSSFWorkbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet();
    int rownum = 0;

    // 标题

    Row title = sheet.createRow(rownum++);
    Cell title_cell = title.createCell(0);
    title_cell.setCellValue(customer_2_name + customer_0or1_name + "前端设备明细表");
    CellStyle title_style = wb.createCellStyle();
    Font title_font = wb.createFont();
    title_font.setFontHeightInPoints((short) 16);
    // f.setColor(IndexedColors.RED.getIndex());
    title_font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    title_style.setFont(title_font);
    title_style.setAlignment(CellStyle.ALIGN_CENTER);
    title_style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    title_cell.setCellStyle(title_style);
    // 和并单元格
    // sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) 15));
    // ===========================================================================================
    rownum = exportFrontEquipListReport_header_assetclean(list_subtype_prod, rownum, wb, sheet);
    // =============================================================================================
    // 开始构建整个excel的文件
    // 处理对应的品名在excel的哪一列
    Map<String, Integer> prod_col_index_map = new HashMap<String, Integer>();
    int cellIndex = 3;
    for (FrontEquipListReport_subtype subtype : list_subtype_prod) {
      for (FrontEquipListReport_prod prod : subtype.getProds()) {
        prod_col_index_map.put(prod.getProd_id(), cellIndex);
        cellIndex = cellIndex + 2;
      }
    }

    if (list != null && list.size() > 0) {
      int i = 1;
      for (FrontEquipListReport customer : list) {
        Row row = sheet.createRow(rownum++);
        Cell cell_prod_0 = row.createCell(0);
        cell_prod_0.setCellValue(i);
        // cell_prod_0.setCellStyle(style);
        Cell cell_prod_1 = row.createCell(1);
        cell_prod_1.setCellValue(customer.getPole_code());
        Cell cell_prod_2 = row.createCell(2);
        cell_prod_2.setCellValue(customer.getPole_name());
        for (FrontEquipListReport_prod prod : customer.getProdes()) {
          Cell cell_prod = row.createCell(prod_col_index_map.get(prod.getProd_id()));
          cell_prod.setCellValue(prod.getNum());
          // cell_prod.setCellStyle(style);

          cell_prod = row.createCell(prod_col_index_map.get(prod.getProd_id()) + 1);
          cell_prod.setCellValue(prod.getValue_net().doubleValue());
        }
        i++;
      }
      // 对标题行 进行单元格合并
      sheet.addMergedRegion(
          new CellRangeAddress(0, (short) 0, 0, (short) prod_col_index_map.size()));
    }
    sheet.createFreezePane(3, 3);

    // 添加总计一行
    CellStyle style_sum = wb.createCellStyle();
    Font style_sum_font = wb.createFont();
    style_sum_font.setFontHeightInPoints((short) 12);
    // f.setColor(IndexedColors.RED.getIndex());
    style_sum_font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style_sum.setFont(style_sum_font);
    style_sum.setAlignment(CellStyle.ALIGN_RIGHT);
    style_sum.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    Row row_sum = sheet.createRow(rownum++);
    Cell cell_sum_2 = row_sum.createCell(2);
    cell_sum_2.setCellValue("小计:");
    cell_sum_2.setCellStyle(style_sum);
    for (int i = 3; i < cellIndex; i++) {
      String col = CellReference.convertNumToColString(i);

      Cell cell_sum = row_sum.createCell(i);
      // =SUM(C4:C29) 从第4行开始到最后一样
      // cell_sum.setCellValue("SUM("+col+"4:"+col+(rownum-1)+")");
      cell_sum.setCellFormula("SUM(" + col + "5:" + col + (rownum - 1) + ")");
      cell_sum.setCellStyle(style_sum);

      Cell cell_net = row_sum.createCell(i);
      cell_net.setCellFormula("SUM(" + col + "5:" + col + (rownum - 1) + ")");
      cell_net.setCellStyle(style_sum);
    }

    String filename = customer_2_name + customer_0or1_name + "前端设备明细表-净资产.xlsx";
    // FileOutputStream out = new FileOutputStream(filename);
    response.setHeader(
        "content-disposition",
        "attachment; filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1"));
    // response.setContentType("application/vnd.ms-excel;charset=uft-8");
    response.setContentType(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=uft-8");

    OutputStream out = response.getOutputStream();
    wb.write(out);

    out.flush();
    out.close();
  }
Exemplo n.º 13
0
  /**
   * Builds the columns' headers recursively with this order:
   * |------------------------------------------| | 1 | 9 |
   * |------------------------------------------| | 2 | 5 | 10 |
   * |-----------|-----------------|------------| | 3 | 4 | 6 | 7 | 8 | 11 | 12 |
   * |------------------------------------------|
   *
   * @param sheet The sheet of the XLS file
   * @param siblings The siblings nodes of the headers structure
   * @param rowNum The row number where the siblings must be inserted
   * @param columnNum The column number where the first sibling must be inserted
   * @param createHelper The file creation helper
   * @param dimensionCellStyle The cell style for cells containing dimensions (i.e. attributes'
   *     names)
   * @param memberCellStyle The cell style for cells containing members (i.e. attributes' values)
   * @throws JSONException
   */
  protected void buildColumnsHeader(
      Sheet sheet,
      CrossTab cs,
      List<Node> siblings,
      int rowNum,
      int columnNum,
      CreationHelper createHelper,
      Locale locale,
      CellStyle memberCellStyle,
      CellStyle dimensionCellStyle)
      throws JSONException {
    int columnCounter = columnNum;

    for (int i = 0; i < siblings.size(); i++) {
      Node aNode = (Node) siblings.get(i);
      List<Node> childs = aNode.getChilds();
      Row row = sheet.getRow(rowNum);
      Cell cell = row.createCell(columnCounter);
      String text = (String) aNode.getDescription();
      if (!cs.isMeasureOnRow() && (childs == null || childs.size() <= 0)) {
        // apply the measure scale factor
        text = MeasureScaleFactorOption.getScaledName(text, cs.getMeasureScaleFactor(text), locale);
      }

      cell.setCellValue(createHelper.createRichTextString(text));
      cell.setCellType(this.getCellTypeString());
      int descendants = aNode.getLeafsNumber();
      if (descendants > 1) {
        sheet.addMergedRegion(
            new CellRangeAddress(
                rowNum, // first row (0-based)
                rowNum, // last row  (0-based)
                columnCounter, // first column (0-based)
                columnCounter + descendants - 1 // last column  (0-based)
                ));
      }

      /*
       * Now we have to set the style properly according to the nature of
       * the node: if it contains the name of a dimension or a member.
       * Since the structure foresees that a list of members follows a
       * dimension, we calculate the position of the node with respect to
       * the leaves; in case it is odd, the cell contains a dimension; in
       * case it is even, the cell contains a dimension.
       */
      int distanceToLeaves = aNode.getDistanceFromLeaves();
      if (!cs.isMeasureOnRow()) {
        distanceToLeaves--;
      }
      boolean isDimensionNameCell = distanceToLeaves > 0 && (distanceToLeaves % 2) == 1;
      if (isDimensionNameCell) {
        cell.setCellStyle(dimensionCellStyle);
      } else {
        cell.setCellStyle(memberCellStyle);
      }

      if (childs != null && childs.size() > 0) {
        buildColumnsHeader(
            sheet,
            cs,
            childs,
            rowNum + 1,
            columnCounter,
            createHelper,
            locale,
            memberCellStyle,
            dimensionCellStyle);
      }
      int increment = descendants > 1 ? descendants : 1;
      columnCounter = columnCounter + increment;
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession ss = request.getSession();
    Account ac = (Account) ss.getAttribute("ac");
    int cId = Integer.parseInt((Long) ss.getAttribute("cId") + "");
    Course c = Course.getCourseByID(cId);

    Workbook wb = new XSSFWorkbook();
    Map<String, CellStyle> styles = createStyles(wb);

    Sheet sheet = wb.createSheet("scoresheet");
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);

    Row titleRow = sheet.createRow(0);
    titleRow.setHeightInPoints(45);
    Cell titleCell = titleRow.createCell(0);
    titleCell.setCellValue("Score sheet of " + c.getName() + " course");
    titleCell.setCellStyle(styles.get("title"));
    sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$N$1"));

    List<Account> listStudentScore = (List<Account>) ss.getAttribute("listStudentScore");
    int rownum = 2;
    int cellcount = 1;
    Row sumRow = sheet.createRow(rownum);
    sumRow.setHeightInPoints(55);
    Cell cell;
    cell = sumRow.createCell(0);
    cell.setCellValue("Student name");
    cell.setCellStyle(styles.get("header"));
    int countback = listStudentScore.get(0).getListStudentScore().size();
    int maxScore = 0;
    for (int i = countback - 1; i >= 0; i--) {
      cell = sumRow.createCell(cellcount);
      UserScore u = listStudentScore.get(0).getListStudentScore().get(i);
      cell.setCellValue("(" + cellcount + ") " + u.getAm_name() + " (" + u.getFull_mark() + ")");
      cell.setCellStyle(styles.get("header"));
      cellcount++;
      maxScore += u.getFull_mark();
    }
    cell = sumRow.createCell(cellcount);
    cell.setCellValue("Total (" + maxScore + ")");
    cell.setCellStyle(styles.get("header"));
    rownum++;

    for (Account account : listStudentScore) {
      sumRow = sheet.createRow(rownum);
      sumRow.setHeightInPoints(35);
      cell = sumRow.createCell(0);
      cell.setCellValue(account.getFirstname() + " " + account.getLastname());
      int j = 1;
      for (int i = account.getListStudentScore().size() - 1; i >= 0; i--) {
        UserScore usc = (UserScore) account.getListStudentScore().get(i);
        cell = sumRow.createCell(j);
        Assignment a = null;
        if (usc.getAss_type().equalsIgnoreCase("web")) {
          a = Assignment.getAmTimeByAmID(usc.getStof().getAm_id());
          String status = Assignment.lastedSentStatus(usc.getStof().getLasted_send_date(), a);
          if (status.equalsIgnoreCase("ontime")
              || status.equalsIgnoreCase("hurryup")
              || status.equalsIgnoreCase("late")) {
            cell.setCellValue(usc.getStof().getScore());
          } else {
            status = Assignment.calculateTime(a);
            if (status.equalsIgnoreCase("miss")) {
              cell.setCellValue(usc.getStof().getScore());
            } else {
              cell.setCellValue("-");
            }
          }

        } else if (usc.getAss_type().equalsIgnoreCase("file")) {
          a = Assignment.getAmTimeByAmID(usc.getStf().getAm_id());
          String status = Assignment.lastedSentStatus(usc.getStf().getLasted_send_date(), a);
          if (status.equalsIgnoreCase("ontime")
              || status.equalsIgnoreCase("hurryup")
              || status.equalsIgnoreCase("late")) {
            cell.setCellValue(usc.getStf().getScore());
          } else {
            status = Assignment.calculateTime(a);
            if (status.equalsIgnoreCase("miss")) {
              cell.setCellValue(usc.getStf().getScore());
            } else {
              cell.setCellValue("-");
            }
          }
        }
        j++;
      }
      cell = sumRow.createCell(j);
      int lastcol = account.getListStudentScore().size();

      // calculate column
      int dv = lastcol / 26;
      String coltmp = "";
      for (int i = 0; i < dv; i++) {
        coltmp += "A";
      }
      coltmp += (char) ('A' + (lastcol - (dv * 26)));
      System.out.println(coltmp);
      //

      String ref = (char) ('A' + 1) + "" + (rownum + 1) + ":" + coltmp + (rownum + 1);
      System.out.println(ref);
      cell.setCellFormula("SUM(" + ref + ")");
      rownum++;
    }

    // Write the output to a file
    String filename = "scoresheet_" + c.getName() + ".xlsx";
    String file = getServletContext().getRealPath("/") + "/file/scoresheet/" + filename;
    //        String file = "C:\\Users\\Orarmor\\Desktop\\scoresheet.xlsx";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();

    response.sendRedirect("file/scoresheet/" + filename);

    //
    //        Workbook wb = new XSSFWorkbook();
    //        Sheet sheet = wb.createSheet("scoresheet");
    //        PrintSetup printSetup = sheet.getPrintSetup();
    //        printSetup.setLandscape(true);
    //        sheet.setFitToPage(true);
    //        sheet.setHorizontallyCenter(true);
    //
    //        //title row
    //        Row titleRow = sheet.createRow(0);
    //        titleRow.setHeightInPoints(45);
    //        Cell titleCell = titleRow.createCell(0);
    //        titleCell.setCellValue("Score sheet of " + "...." + " course");
    //        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$1:$D$1"));
    //
    //        //row with totals below
    //        int rownum = 2;
    //        Row sumRow = sheet.createRow(rownum);
    //       sumRow.setHeightInPoints(35);
    //        Cell cell;
    //        cell = sumRow.createCell(0);
    //        cell.setCellValue("Name:");
    //
    //        for (int j = 1; j < 12; j++) {
    //            cell = sumRow.createCell(j);
    //            String ref = (char) ('A' + j) + "3:" + (char) ('A' + j) + "12";
    //            cell.setCellFormula("SUM(" + ref + ")");
    //        }
    //
    //        // Write the output to a file
    //        String file = "C:\\Users\\Orarmor\\Desktop\\scoresheet.xlsx";
    //        FileOutputStream out = new FileOutputStream(file);
    //        wb.write(out);
    //        out.close();
  }
Exemplo n.º 15
0
  @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  +++++++++++++");
  }
Exemplo n.º 16
0
  @Override
  public BordeSeccion generar(BordeSeccion borde, ContextoSeccion contexto, ReporteCliente datos) {
    Sheet sheet = contexto.getSheet();
    XSSFWorkbook wb = contexto.getWb();
    int initialRow = borde.getUpperRow();
    int initialColumn = borde.getLeftColumn();
    BordeSeccion r = new BordeSeccion();
    r.setLeftColumn(initialColumn);
    r.setUpperRow(initialRow);

    // escribir el primer renglon
    Row row = getRow(sheet, initialRow);
    Cell cell = row.createCell(initialColumn);
    cell.setCellValue("Auto");
    // estilo .-.
    XSSFCellStyle cellStyle = wb.createCellStyle();
    addHeaderStyle(cellStyle, wb);
    addBorders(wb, cellStyle, CellStyle.BORDER_THIN);
    cell.setCellStyle(cellStyle);
    for (int i = 1; i < encabezados.length; i++) {
      cell = row.createCell(initialColumn + i);
      cellStyle = wb.createCellStyle();
      addBorders(wb, cellStyle, CellStyle.BORDER_THIN);
      cell.setCellStyle(cellStyle);
    }
    // merge de celdas
    sheet.addMergedRegion(
        new CellRangeAddress(
            initialRow, // first row (0-based)
            initialRow, // last row  (0-based)
            initialColumn, // first column (0-based)
            initialColumn + 7 // last column  (0-based)
            ));
    // segundo renglon encabezado
    initialRow = initialRow + 1;
    row = getRow(sheet, initialRow);
    for (int i = 0; i < encabezados.length; i++) {
      cell = row.createCell(initialColumn + i);
      cell.setCellValue(encabezados[i]);
      cellStyle = wb.createCellStyle();
      addHeaderStyle(cellStyle, wb);
      addBorders(wb, cellStyle, CellStyle.BORDER_THIN);
      cell.setCellStyle(cellStyle);
    }
    // tercer renglon encabezado
    initialRow = initialRow + 1;
    row = getRow(sheet, initialRow);
    for (int i = 0; i < atributos.length; i++) {
      cell = row.createCell(initialColumn + i);
      try {
        cell.setCellValue(PropertyUtils.getProperty(datos, "auto." + atributos[i]).toString());
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
        cell.setCellValue("");
      }
      cellStyle = wb.createCellStyle();
      addBorders(wb, cellStyle, CellStyle.BORDER_THIN);
      cell.setCellStyle(cellStyle);
    }

    r.setLowerRow(initialRow);
    r.setRightColumn(initialColumn + 7);
    paintBorder(wb, sheet, CellStyle.BORDER_MEDIUM, r);
    return r;
  }