Exemple #1
0
 /**
  * セルに文字列を出力する
  *
  * @param cell 対象セル
  * @param object 出力データ
  * @param style セルスタイル
  * @param zeroValue 値が0の時に設定する値
  */
 private static void setData(XSSFCell cell, Object object, XSSFCellStyle style, String zeroValue) {
   if (style != null) {
     cell.setCellStyle(style);
   }
   if (object instanceof String) {
     cell.setCellType(XSSFCell.CELL_TYPE_STRING);
     cell.setCellValue((String) object);
   } else if (object instanceof Integer) {
     Integer integer = (Integer) object;
     if (0 == integer) {
       cell.setCellType(XSSFCell.CELL_TYPE_STRING);
       cell.setCellValue(zeroValue);
     } else {
       cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
       cell.setCellValue((Integer) object);
     }
   } else if (object instanceof Double) {
     cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
     if (Double.isNaN((Double) object)) {
       cell.setCellValue(zeroValue);
     } else {
       Double value = (Double) object;
       if (0 == value.compareTo((Double) 0.0)) {
         cell.setCellValue(zeroValue);
       } else {
         cell.setCellValue((Double) object);
       }
     }
   }
 }
 public static void copyCell(XSSFCell oldCell, XSSFCell newCell) {
   try {
     switch (oldCell.getCellType()) {
       case XSSFCell.CELL_TYPE_STRING:
         newCell.setCellValue(oldCell.getStringCellValue());
         break;
       case XSSFCell.CELL_TYPE_NUMERIC:
         newCell.setCellValue(oldCell.getNumericCellValue());
         break;
       case XSSFCell.CELL_TYPE_BLANK:
         newCell.setCellType(XSSFCell.CELL_TYPE_BLANK);
         break;
       case XSSFCell.CELL_TYPE_BOOLEAN:
         newCell.setCellValue(oldCell.getBooleanCellValue());
         break;
       case XSSFCell.CELL_TYPE_ERROR:
         newCell.setCellErrorValue(oldCell.getErrorCellValue());
         break;
       case XSSFCell.CELL_TYPE_FORMULA:
         newCell.setCellFormula(oldCell.getCellFormula());
         break;
       default:
         break;
     }
   } catch (Exception ex) {
     System.out.println("Error in writing Cell in reject excel file :: " + ex.getMessage());
     ex.printStackTrace();
   }
 }
Exemple #3
0
 /**
  * 指定行を0で埋める
  *
  * @param sheet 編集対象シート
  * @param nRow 行番号
  * @param nStartColumn 開始列番号
  * @param nEndColumn 終了列番号
  */
 public static void setZero(XSSFSheet sheet, int nRow, int nStartColumn, int nEndColumn) {
   XSSFRow row = getRowAnyway(sheet, nRow);
   for (int nIndex = nStartColumn; nIndex <= nEndColumn; nIndex++) {
     XSSFCell cell = getCellAnyway(row, nIndex);
     cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
     cell.setCellValue((double) 0);
   }
 }
 /**
  * @param oldCell
  * @param newCell
  * @param styleMap
  */
 public static void copyCell(
     XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) {
   if (styleMap != null) {
     if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) {
       newCell.setCellStyle(oldCell.getCellStyle());
     } else {
       int stHashCode = oldCell.getCellStyle().hashCode();
       XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
       if (newCellStyle == null) {
         newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
         newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
         styleMap.put(stHashCode, newCellStyle);
       }
       newCell.setCellStyle(newCellStyle);
     }
   }
   switch (oldCell.getCellType()) {
     case HSSFCell.CELL_TYPE_STRING:
       newCell.setCellValue(oldCell.getStringCellValue());
       break;
     case HSSFCell.CELL_TYPE_NUMERIC:
       newCell.setCellValue(oldCell.getNumericCellValue());
       break;
     case HSSFCell.CELL_TYPE_BLANK:
       newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);
       break;
     case HSSFCell.CELL_TYPE_BOOLEAN:
       newCell.setCellValue(oldCell.getBooleanCellValue());
       break;
     case HSSFCell.CELL_TYPE_ERROR:
       newCell.setCellErrorValue(oldCell.getErrorCellValue());
       break;
     case HSSFCell.CELL_TYPE_FORMULA:
       newCell.setCellFormula(oldCell.getCellFormula());
       break;
     default:
       break;
   }
 }
  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 XSSFWorkbook exportAllStatistics(
      List<StatisticData> statistics, Interview interview, ByteArrayOutputStream out)
      throws IOException {
    /*NULL is correct value*/
    try (XSSFWorkbook book = new XSSFWorkbook()) {
      XSSFSheet sheet = book.createSheet(SHEET_NAME);
      int rowNumber = 0;

      XSSFRow mainHeader = sheet.createRow(rowNumber++);
      XSSFCell cell = mainHeader.createCell(0);
      cell.setCellType(Cell.CELL_TYPE_STRING);
      cell.setCellValue(HEADER_PREFIX + interview.getName() + "\"");
      makeCellAutosizeAndBold(book, mainHeader);

      rowNumber++;

      for (StatisticData statistic : statistics) {
        /*Add question text*/
        XSSFRow row = sheet.createRow(rowNumber++);
        XSSFCell questionText = row.createCell(0);
        questionText.setCellType(Cell.CELL_TYPE_STRING);
        questionText.setCellValue(QUESTION_PREFIX + statistic.getQuestionText());

        XSSFRow tableHeader = sheet.createRow(rowNumber++);
        XSSFCell c1 = tableHeader.createCell(0);
        XSSFCell c2 = tableHeader.createCell(1);
        XSSFCell c3 = tableHeader.createCell(2);
        XSSFCell c4 = tableHeader.createCell(3);

        c1.setCellType(Cell.CELL_TYPE_STRING);
        c2.setCellType(Cell.CELL_TYPE_NUMERIC);
        c3.setCellType(Cell.CELL_TYPE_NUMERIC);
        c4.setCellType(Cell.CELL_TYPE_STRING);

        c1.setCellValue(ANSWER_CELL_HEADER);
        c2.setCellValue(PEOPLE_COUNT_HEADER);
        c3.setCellValue(PERCENT_HEADER);
        c4.setCellValue(RESPONDENTS_HEADER);

        makeCellAutosizeAndBold(book, tableHeader);

        Map<String, Object[]> answerData = statistic.getAnswerData();

        for (String key : answerData.keySet()) {
          XSSFRow answer = sheet.createRow(rowNumber++);
          XSSFCell answerText = answer.createCell(0);
          XSSFCell peopleResponded = answer.createCell(1);
          XSSFCell percentResponded = answer.createCell(2);
          XSSFCell respondents = answer.createCell(3);

          answerText.setCellType(Cell.CELL_TYPE_STRING);
          peopleResponded.setCellType(Cell.CELL_TYPE_NUMERIC);
          percentResponded.setCellType(Cell.CELL_TYPE_NUMERIC);
          respondents.setCellType(Cell.CELL_TYPE_STRING);

          answerText.setCellValue(key);
          Object[] values = answerData.get(key);

          peopleResponded.setCellValue(values[0].toString());
          percentResponded.setCellValue(values[1].toString().replace(",", "."));
          respondents.setCellValue(userAnswerService.getRespondentListHowLine(interview, key));

          makeCellsAutosize(book, answer);
        }

        rowNumber++;
      }

      book.write(out);
      return book;
    }
  }
Exemple #7
0
  public static boolean writeMultArray2XLSXFile(
      String fileName,
      List<List<String[]>> arrys,
      List<String> sheetLabels,
      boolean hasHead,
      int indexKey)
      throws Exception {

    if (arrys.isEmpty()) {
      System.err.println("No input data!");
      return false;
    }

    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFCellStyle headStyle = wb.createCellStyle();
    // apply custom font to the text in the comment
    XSSFFont font = wb.createFont();

    font.setFontName("Courier New");
    font.setFontHeightInPoints((short) 10);
    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.RED.index);

    headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    headStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    headStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    headStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    headStyle.setLocked(true);
    headStyle.setFont(font);

    XSSFCellStyle bodyStyle = wb.createCellStyle();
    bodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    XSSFCellStyle markedBodyStyle = wb.createCellStyle();
    markedBodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    markedBodyStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    markedBodyStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    String lastKey = null;
    int switcher = -1;
    XSSFCell cell = null;
    String[] titleNames = null;
    int d = 0;
    for (List<String[]> arry : arrys) {
      XSSFSheet sheet1 = wb.createSheet(sheetLabels.get(d));
      if (hasHead) {
        titleNames = (String[]) arry.get(0);
      }
      int columnNum = ((String[]) arry.get(0)).length;

      for (int i = 0; i < columnNum; i++) {
        sheet1.setColumnWidth(i, (short) ((30 * 6) / ((double) 1 / 20)));
      }

      int rowIndex = 0;
      // create titile row
      XSSFRow row = sheet1.createRow(rowIndex);

      if (titleNames != null) {
        for (int i = 0; i < columnNum; i++) {
          cell = row.createCell(i);
          cell.setCellValue(titleNames[i]);
          cell.setCellStyle(headStyle);
        }
        rowIndex++;
      }
      int rowNum = arry.size();

      for (int i = rowIndex; i < rowNum; i++) {
        row = sheet1.createRow((i));
        String[] line = (String[]) arry.get(i);
        columnNum = line.length;
        if (indexKey >= 0) {
          if (lastKey == null && line[indexKey] != null) {
            lastKey = line[indexKey];
            switcher *= -1;
          } else if (lastKey != null && line[indexKey] == null) {
            lastKey = line[indexKey];
            switcher *= -1;
          } else if (lastKey == null && line[indexKey] == null) {
          } else {
            if (!lastKey.equals(line[indexKey])) {
              switcher *= -1;
              lastKey = line[indexKey];
            }
          }
        } else {
          switcher = 1;
        }
        for (int j = 0; j < columnNum; j++) {
          cell = row.createCell(j);
          if (switcher > 0) {
            cell.setCellStyle(bodyStyle);
          } else {
            cell.setCellStyle(markedBodyStyle);
          }

          if (line[j] != null) {
            if (Util.isNumeric(line[j])) {
              // org.?apache.?poi.?XSSF.?usermodel.?XSSFCell.CELL_TYPE_NUMERIC
              cell.setCellType(0);
              cell.setCellValue(Double.parseDouble(line[j]));
            } else {
              cell.setCellValue(line[j]);
            }
          } else {
            cell.setCellValue(".");
          }
        }
      }

      d++;
    }

    // Write the output to a inFile
    FileOutputStream fileOut = new FileOutputStream(fileName);
    wb.write(fileOut);
    fileOut.close();

    return true;
  }
Exemple #8
0
  public static boolean convertTextFile2XLSXFile(
      String inFileName, String outFileName, boolean hasHead, int indexKey) throws Exception {
    BufferedReader br = LocalFileFunc.getBufferedReader(inFileName);
    String line = br.readLine();
    if (line == null) {
      return false;
    }
    String[] cells1 = Util.tokenize(line, '\t');
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet1 = wb.createSheet("Data");

    int columnNum = cells1.length;
    for (int i = 0; i < columnNum; i++) {
      sheet1.setColumnWidth(i, (short) ((30 * 6) / ((double) 1 / 20)));
    }

    XSSFCellStyle headStyle = wb.createCellStyle();
    // apply custom font to the text in the comment
    XSSFFont font = wb.createFont();
    font.setFontName("Courier New");
    font.setFontHeightInPoints((short) 10);
    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.RED.index);

    headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    headStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    headStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    headStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    headStyle.setLocked(true);
    headStyle.setFont(font);

    XSSFCellStyle bodyStyle = wb.createCellStyle();
    bodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    XSSFCellStyle markedBodyStyle = wb.createCellStyle();
    markedBodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    markedBodyStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
    markedBodyStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    int rowIndex = 0;
    // create titile row
    XSSFRow row = sheet1.createRow(rowIndex);

    String lastKey = null;
    int switcher = -1;
    XSSFCell cell = null;
    if (hasHead) {
      for (int i = 0; i < columnNum; i++) {
        cell = row.createCell(i);
        cell.setCellValue(cells1[i]);
        cell.setCellStyle(headStyle);
      }
    } else {
      for (int i = 0; i < columnNum; i++) {
        cell = row.createCell(i);
        cell.setCellValue(cells1[i]);
        cell.setCellStyle(bodyStyle);
      }
    }
    rowIndex++;
    while ((line = br.readLine()) != null) {
      cells1 = Util.tokenize(line, '\t');
      row = sheet1.createRow((rowIndex));
      columnNum = cells1.length;
      if (indexKey >= 0) {
        if (lastKey == null && cells1[indexKey] != null) {
          lastKey = cells1[indexKey];
          switcher *= -1;
        } else if (lastKey != null && cells1[indexKey] == null) {
          lastKey = cells1[indexKey];
          switcher *= -1;
        } else if (lastKey == null && cells1[indexKey] == null) {
        } else {
          if (!lastKey.equals(cells1[indexKey])) {
            switcher *= -1;
            lastKey = cells1[indexKey];
          }
        }
      } else {
        switcher = 1;
      }
      // System.out.println(cells1[0]);
      for (int j = 0; j < columnNum; j++) {
        cell = row.createCell(j);
        if (switcher > 0) {
          cell.setCellStyle(bodyStyle);
        } else {
          cell.setCellStyle(markedBodyStyle);
        }

        if (cells1[j] != null) {
          if (Util.isNumeric(cells1[j])) {
            // org.?apache.?poi.?XSSF.?usermodel.?XSSFCell.CELL_TYPE_NUMERIC
            cell.setCellType(0);
            cell.setCellValue(Double.parseDouble(cells1[j]));
          } else {
            cell.setCellValue(cells1[j]);
          }
        } else {
          cell.setCellValue(".");
        }
      }
      rowIndex++;
    }
    br.close();
    // Write the output to a inFile
    FileOutputStream fileOut = new FileOutputStream(outFileName);
    wb.write(fileOut);
    fileOut.close();

    return true;
  }
Exemple #9
0
  public static boolean writeArray2XLSXSheet(
      XSSFSheet sheet1, XSSFWorkbook wb, List<String[]> arry, boolean hasHead) throws Exception {
    int rowNum = arry.size();
    if (rowNum == 0) {
      System.err.println("No input data!");
      return false;
    }

    String[] titleNames = null;
    if (hasHead) {
      titleNames = (String[]) arry.get(0);
    }
    int columnNum = ((String[]) arry.get(0)).length;

    for (int i = 0; i < columnNum; i++) {
      sheet1.setColumnWidth((short) i, (short) ((30 * 8) / ((double) 1 / 20)));
    }

    XSSFFont font = wb.createFont();
    font.setFontName("Courier New");
    font.setFontHeightInPoints((short) 10);
    font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    font.setColor(HSSFColor.RED.index);

    XSSFCellStyle headStyle = wb.createCellStyle();
    headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    headStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    headStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    headStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
    headStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    headStyle.setLocked(true);
    headStyle.setFont(font);

    XSSFCellStyle bodyStyle = wb.createCellStyle();
    bodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    bodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);

    XSSFCellStyle markedBodyStyle = wb.createCellStyle();
    markedBodyStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
    markedBodyStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    markedBodyStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
    markedBodyStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);

    int rowIndex = 0;
    // create titile row
    XSSFRow row = sheet1.createRow(rowIndex);

    XSSFCell cell = null;
    if (titleNames != null) {
      for (int i = 0; i < columnNum; i++) {
        cell = row.createCell((short) i);
        cell.setCellValue(titleNames[i]);
        cell.setCellStyle(headStyle);
      }
      rowIndex++;
    }

    for (int i = rowIndex; i < rowNum; i++) {
      row = sheet1.createRow((i));
      String[] line = (String[]) arry.get(i);
      columnNum = line.length;
      for (int j = 0; j < columnNum; j++) {
        cell = row.createCell(j);
        if (line[0] != null) {
          cell.setCellStyle(markedBodyStyle);
        } else {
          cell.setCellStyle(bodyStyle);
        }
        if (line[j] != null) {
          if (Util.isNumeric(line[j])) {
            // org.?apache.?poi.?XSSF.?usermodel.?XSSFCell.CELL_TYPE_NUMERIC
            cell.setCellType(0);
            cell.setCellValue(Double.parseDouble(line[j]));
          } else {
            cell.setCellValue(line[j]);
          }
        } else {
          cell.setCellValue("");
        }
      }
    }
    return true;
  }
Exemple #10
0
  public static boolean writeArray2XLSXFile(
      String FileName, String[] titleNames, List<String[]> arry) throws Exception {
    XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet1 = wb.createSheet("Data");
    int columnNum = titleNames.length;
    int rowNum = arry.size();

    // for (int i = 0; i < columnNum; i++) {
    //  sheet1.setColumnWidth( i, (short) ((30 * 8) / ((double) 1 / 20)));
    // }
    XSSFCellStyle headStyle = wb.createCellStyle();
    // apply custom headFont to the text in the comment
    XSSFFont headFont = wb.createFont();
    headFont.setFontName("Courier New");
    headFont.setFontHeightInPoints((short) 10);
    headFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    headFont.setColor(HSSFColor.BLACK.index);

    headStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    headStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
    headStyle.setFillForegroundColor(HSSFColor.BLACK.index);
    headStyle.setLocked(true);
    headStyle.setFont(headFont);
    headStyle.setBorderTop((short) 2);
    headStyle.setBorderBottom((short) 1);

    XSSFCellStyle contentStyle = wb.createCellStyle();
    // apply custom headFont to the text in the comment
    XSSFFont contentFont = wb.createFont();
    contentFont.setFontName("Courier New");
    contentFont.setFontHeightInPoints((short) 9);
    // headFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
    contentFont.setColor(HSSFColor.BLACK.index);

    contentStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    contentStyle.setFillForegroundColor(HSSFColor.BLACK.index);
    contentStyle.setFont(contentFont);

    // create titile row
    XSSFRow row = sheet1.createRow(0);
    int heandLine = 0;
    XSSFCell cell = null;

    if (titleNames != null) {
      for (int i = 0; i < columnNum; i++) {
        cell = row.createCell(i);
        cell.setCellValue(titleNames[i]);
        cell.setCellStyle(headStyle);
      }
      heandLine++;
    }

    for (int i = 0; i < rowNum; i++) {
      row = sheet1.createRow((i + heandLine));
      String[] line = (String[]) arry.get(i);
      for (int j = 0; j < columnNum; j++) {
        cell = row.createCell(j);
        if (line[j] != null) {
          if (Util.isNumeric(line[j])) {
            // org.?apache.?poi.?XSSF.?usermodel.?XSSFCell.CELL_TYPE_NUMERIC
            cell.setCellType(0);
            cell.setCellValue(Double.parseDouble(line[j]));
          } else {
            cell.setCellValue(line[j]);
          }
        } else {
          cell.setCellValue(".");
        }
      }
    }

    // Write the output to a inFile
    FileOutputStream fileOut = new FileOutputStream(FileName);
    wb.write(fileOut);
    fileOut.close();

    return true;
  }