コード例 #1
0
ファイル: TimesheetDemo.java プロジェクト: zbeboy/exceldemo
  /** 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;
  }
コード例 #2
0
  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);
  }
コード例 #3
0
  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;
  }
コード例 #4
0
ファイル: NaiveBayes.java プロジェクト: hamiltontj/NaiveBayes
  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);
    }
  }