Example usage for org.apache.poi.xssf.usermodel XSSFSheet createRow

List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet createRow

Introduction

In this page you can find the example usage for org.apache.poi.xssf.usermodel XSSFSheet createRow.

Prototype

@Override
public XSSFRow createRow(int rownum) 

Source Link

Document

Create a new row within the sheet and return the high level representation Note: If a row already exists at this position, it is removed/overwritten and any existing cell is removed!

Usage

From source file:org.appdynamics.utilreports.files.ProcessExcelFile.java

private void processEUM(XSSFSheet xsf, GatherEUMInfo eum, String app) {
    //First row is the application
    int rowIndex = 0;
    int cellIndex = 0;
    Row headerRow = xsf.createRow(rowIndex);
    Cell cell_0 = headerRow.createCell(cellIndex);
    cell_0.setCellValue(new StringBuilder().append(AppDUtilReportS.APPLICATION_EQ).append(app).toString());
    cellIndex++;//from   ww w  .  ja va  2  s.c o m
    Cell cell_1 = headerRow.createCell(cellIndex);
    cell_1.setCellValue(
            new StringBuilder().append("EUM Query end time ").append(getDate(eum.getEnd())).toString());

    rowIndex += 2;
    headerRow = xsf.createRow(rowIndex);
    //Second row is the header
    cellIndex = 0;
    cell_0 = headerRow.createCell(cellIndex);
    cell_0.setCellValue(AppDUtilReportS.TIME_RANGE);
    cellIndex++;
    cell_1 = headerRow.createCell(cellIndex);
    cell_1.setCellValue(new StringBuilder().append(eum.getName()).append(" Name").toString());
    cellIndex++;
    Cell cell_2 = headerRow.createCell(cellIndex);
    cell_2.setCellValue(AppDUtilReportS.REQUEST_COUNTS);

    cellIndex = 0;

    rowIndex++;
    //Now we start putting down the data
    String hourRange = AppDUtilReportS.LAST_4_HOURS;
    for (String dBt : eum.get4HourEUM().keySet()) {
        rowIndex++;
        headerRow = xsf.createRow(rowIndex);
        cell_0 = headerRow.createCell(cellIndex);
        cell_0.setCellValue(hourRange);
        cellIndex++;
        cell_1 = headerRow.createCell(cellIndex);
        cell_1.setCellValue(dBt);
        cellIndex++;
        cell_2 = headerRow.createCell(cellIndex);
        cell_2.setCellValue(eum.get4HourEUM().get(dBt));
        cellIndex = 0;
    }

    hourRange = AppDUtilReportS.LAST_24_HOURS;
    for (String dBt : eum.get24HourEUM().keySet()) {
        rowIndex++;
        headerRow = xsf.createRow(rowIndex);
        cell_0 = headerRow.createCell(cellIndex);
        cell_0.setCellValue(hourRange);
        cellIndex++;
        cell_1 = headerRow.createCell(cellIndex);
        cell_1.setCellValue(dBt);
        cellIndex++;
        cell_2 = headerRow.createCell(cellIndex);
        cell_2.setCellValue(eum.get24HourEUM().get(dBt));
        cellIndex = 0;
    }

    hourRange = AppDUtilReportS.LAST_48_HOURS;
    for (String dBt : eum.get48HourEUM().keySet()) {
        rowIndex++;
        headerRow = xsf.createRow(rowIndex);
        cell_0 = headerRow.createCell(cellIndex);
        cell_0.setCellValue(hourRange);
        cellIndex++;
        cell_1 = headerRow.createCell(cellIndex);
        cell_1.setCellValue(dBt);
        cellIndex++;
        cell_2 = headerRow.createCell(cellIndex);
        cell_2.setCellValue(eum.get48HourEUM().get(dBt));
        cellIndex = 0;
    }
    //We are going to create row 0 first
    hourRange = AppDUtilReportS.NORMAL;
    for (String dBt : eum.getNormalEUM().keySet()) {
        rowIndex++;
        headerRow = xsf.createRow(rowIndex);
        cell_0 = headerRow.createCell(cellIndex);
        cell_0.setCellValue(hourRange);
        cellIndex++;
        cell_1 = headerRow.createCell(cellIndex);
        cell_1.setCellValue(dBt);
        cellIndex++;
        cell_2 = headerRow.createCell(cellIndex);
        cell_2.setCellValue(eum.getNormalEUM().get(dBt));
        cellIndex = 0;
    }
}

From source file:org.azkfw.doclet.jaxrs.writer.JAXRSXlsxDocletWriter.java

License:Apache License

private void printSheet(final XSSFWorkbook wb, final XSSFSheet sheet, final APIModel api) {

    ////////////////////////////////////////////////////
    XSSFRow row = null;//from w w w .  j a  va 2 s.c  o m
    XSSFCell cell = null;

    ////////////////////////////////////////////////////

    row = sheet.createRow(1); //////////////////////////
    cell = row.createCell(1, Cell.CELL_TYPE_STRING);
    cell.setCellValue("??");

    cell = row.createCell(5, Cell.CELL_TYPE_STRING);
    cell.setCellValue(s(api.getName()));

    cell = row.createCell(22, Cell.CELL_TYPE_STRING);
    cell.setCellValue("");

    cell = row.createCell(25, Cell.CELL_TYPE_STRING);
    cell.setCellValue("TUF-8");

    row = sheet.createRow(2); //////////////////////////
    cell = row.createCell(1, Cell.CELL_TYPE_STRING);
    cell.setCellValue("URL");
    cell = row.createCell(5, Cell.CELL_TYPE_STRING);
    cell.setCellValue(s(api.getPath()));

    cell = row.createCell(15, Cell.CELL_TYPE_STRING);
    cell.setCellValue("");
    cell = row.createCell(18, Cell.CELL_TYPE_STRING);
    cell.setCellValue("");
}

From source file:org.azkfw.doclet.jaxrs.writer.JAXRSXlsxDocletWriter.java

License:Apache License

private void printSheet(final XSSFWorkbook wb, final XSSFSheet sheet, final List<APIModel> apis) {

    XSSFCell cell = null;//from w  ww.j  av  a2 s  .  c  om
    XSSFRow row = null;

    ////////////////////////////////////////////////////
    XSSFFont fontBold = wb.createFont();
    fontBold.setBold(true);

    CellStyle styleHeader = wb.createCellStyle();
    styleHeader.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styleHeader.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
    styleHeader.setFont(fontBold);
    styleHeader.setBorderTop(CellStyle.BORDER_THIN);
    styleHeader.setBorderLeft(CellStyle.BORDER_THIN);
    styleHeader.setBorderRight(CellStyle.BORDER_THIN);
    styleHeader.setBorderBottom(CellStyle.BORDER_DOUBLE);

    row = sheet.createRow(0); //////////////////////////
    cell = row.createCell(1, Cell.CELL_TYPE_STRING);

    CellStyle style1 = wb.createCellStyle();
    style1.setFont(fontBold);
    cell.setCellStyle(style1);
    cell.setCellValue("I/F (API) ");

    row = sheet.createRow(1); //////////////////////////
    cell = row.createCell(1, Cell.CELL_TYPE_STRING);
    cell.setCellValue("API???");

    row = sheet.createRow(4); //////////////////////////
    cell = row.createCell(1, Cell.CELL_TYPE_STRING);
    cell.setCellValue("ID");
    cell.setCellStyle(styleHeader);
    cell = row.createCell(2, Cell.CELL_TYPE_STRING);
    cell.setCellValue("Group");
    cell.setCellStyle(styleHeader);
    cell = row.createCell(3, Cell.CELL_TYPE_STRING);
    cell.setCellValue("Name");
    cell.setCellStyle(styleHeader);
    cell = row.createCell(4, Cell.CELL_TYPE_STRING);
    cell.setCellValue("Comment");
    cell.setCellStyle(styleHeader);

    int offsetRow = 5;
    int offsetCol = 1;
    for (int i = 0; i < apis.size(); i++) {
        APIModel api = apis.get(i);

        row = sheet.createRow(offsetRow + i);

        cell = row.createCell(offsetCol + 0, Cell.CELL_TYPE_STRING);
        cell.setCellValue(s(api.getId()));

        cell = row.createCell(offsetCol + 2, Cell.CELL_TYPE_STRING);
        cell.setCellValue(s(api.getName()));

        cell = row.createCell(offsetCol + 3, Cell.CELL_TYPE_STRING);
        cell.setCellValue(s(api.getComment()));
    }
}

From source file:org.azkfw.document.database.xlsx.XLSXWriter.java

License:Apache License

private XSSFSheet createTableListSheet(final DatabaseModel datasource, final XSSFSheet sheet) {
    // /*from   w ww.  j a  va 2 s .c  om*/
    sheet.setColumnWidth(0, 640 * 1);
    sheet.setColumnWidth(1, 640 * 2); // No
    sheet.setColumnWidth(2, 640 * 10); // ???
    sheet.setColumnWidth(3, 640 * 10); // ???
    sheet.setColumnWidth(4, 640 * 15); // 
    sheet.setColumnWidth(5, 640 * 1);

    /////////////////////////////////////////////////////////////////////
    XSSFCellStyle styleLabel = workbook.createCellStyle();
    styleLabel.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styleLabel.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
    styleLabel.setFont(fontLabel);
    styleLabel.setBorderTop(CellStyle.BORDER_THIN);
    styleLabel.setBorderBottom(CellStyle.BORDER_THIN);
    styleLabel.setBorderLeft(CellStyle.BORDER_THIN);
    styleLabel.setBorderRight(CellStyle.BORDER_THIN);

    XSSFCellStyle styleValue1 = workbook.createCellStyle();
    styleValue1.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styleValue1.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    styleValue1.setFont(fontValue);
    styleValue1.setBorderTop(CellStyle.BORDER_DOTTED);
    styleValue1.setBorderBottom(CellStyle.BORDER_DOTTED);
    styleValue1.setBorderLeft(CellStyle.BORDER_THIN);
    styleValue1.setBorderRight(CellStyle.BORDER_THIN);

    XSSFCellStyle styleValue2 = workbook.createCellStyle();
    styleValue2.setFillPattern(CellStyle.SOLID_FOREGROUND);
    styleValue2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
    styleValue2.setFont(fontLink);
    styleValue2.setBorderTop(CellStyle.BORDER_DOTTED);
    styleValue2.setBorderBottom(CellStyle.BORDER_DOTTED);
    styleValue2.setBorderLeft(CellStyle.BORDER_THIN);
    styleValue2.setBorderRight(CellStyle.BORDER_THIN);

    /////////////////////////////////////////////////////////////////////
    XSSFRow row = null;
    @SuppressWarnings("unused")
    XSSFCell cell = null;
    int rowIndex = 1;

    ////////////////////////////////////////////////////////////////////////////
    // 
    ////////////////////////////////////////////////////////////////////////////

    row = sheet.createRow(rowIndex); ///////////////////////////////////////////
    cell = createCell(1, Strings.get("doc.table_list"), styleTitle, row);

    List<TableModel> tables = datasource.getTables();

    short top = BD_RECT;
    short bottom = CellStyle.BORDER_THIN;
    if (0 == tables.size()) {
        bottom = BD_RECT;
    }

    rowIndex++;
    row = sheet.createRow(rowIndex); ///////////////////////////////////////////
    cell = createCell(1, Strings.get("doc.no"),
            styleManager.get(defStyleLabel, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
    cell = createCell(2, Strings.get("doc.logic_table_name"),
            styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
    cell = createCell(3, Strings.get("doc.physical_table_name"),
            styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
    cell = createCell(4, Strings.get("doc.memo"),
            styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);

    rowIndex++;
    for (int i = 0; i < tables.size(); i++) {
        int bufRowIndex = rowIndex + i;
        TableModel table = tables.get(i);

        Hyperlink link = createTableLink(table.getName());

        top = CellStyle.BORDER_DOTTED;
        bottom = CellStyle.BORDER_DOTTED;
        if (i == 0) {
            top = CellStyle.BORDER_THIN;
        }
        if (i + 1 == tables.size()) {
            bottom = BD_RECT;
        }

        row = sheet.createRow(bufRowIndex); ///////////////////////////////////////////
        cell = createCell(1, String.format("%d", i + 1),
                styleManager.get(defStyleListValueNo, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(2, table.getLabel(),
                styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(3, table.getName(), styleManager.get(defStyleListValueLink, top, bottom,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), link, row);
        cell = createCell(4, table.getComment(),
                styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
    }
    rowIndex += tables.size();

    workbook.setPrintArea(workbook.getSheetIndex(getTableListSheetName()), 0, 5, 0, rowIndex);
    sheet.setAutobreaks(true);
    XSSFPrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setFitWidth((short) 1);
    printSetup.setScale((short) 95);

    return sheet;
}

From source file:org.azkfw.document.database.xlsx.XLSXWriter.java

License:Apache License

private XSSFSheet createTableSheet(final DatabaseModel datasource, final TableModel table,
        final XSSFSheet sheet) {

    // /*from   ww w.  j  ava  2  s. c  o m*/
    for (int i = 0; i < 39; i++) {
        sheet.setColumnWidth(i, 640);
    }

    /////////////////////////////////////////////////////////////////////
    XSSFRow row = null;
    @SuppressWarnings("unused")
    XSSFCell cell = null;
    int rowIndex = 1;

    ////////////////////////////////////////////////////////////////////////////
    // 
    ////////////////////////////////////////////////////////////////////////////
    {
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, Strings.get("doc.table_info"), styleTitle, row);

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 7, Strings.get("doc.system_name"),
                styleManager.get(defStyleLabel, BD_RECT, CellStyle.BORDER_THIN, BD_RECT, CellStyle.BORDER_THIN),
                row);
        cell = createCell(8, 12, option.getSystemName(), styleManager.get(defStyleHeadValue, BD_RECT,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(20, 3, Strings.get("doc.creator"), styleManager.get(defStyleLabel, BD_RECT,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(23, 6, option.getCreateUser(), styleManager.get(defStyleHeadValue, BD_RECT,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(29, 3, Strings.get("doc.create_day"), styleManager.get(defStyleLabel, BD_RECT,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(32, 6, toString(option.getCreateDate()), styleManager.get(defStyleHeadValue, BD_RECT,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 7));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 19));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 20, 22));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 23, 28));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 29, 31));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 32, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 7, Strings.get("doc.sub_system_name"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(8, 12, option.getSubSystemName(), styleManager.get(defStyleHeadValue,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(20, 3, Strings.get("doc.updater"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(23, 6, option.getUpdateUser(), styleManager.get(defStyleHeadValue,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(29, 3, Strings.get("doc.update_day"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(32, 6, toString(option.getUpdateDate()), styleManager.get(defStyleHeadValue,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 7));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 19));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 20, 22));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 23, 28));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 29, 31));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 32, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 7, Strings.get("doc.schema_name"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(8, 12, table.getSchema().getName(), styleManager.get(defStyleHeadValue,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(20, 3, "", styleManager.get(defStyleLabel, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(23, 15, "", styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 7));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 19));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 20, 22));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 23, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 7, Strings.get("doc.logic_table_name"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(8, 12, table.getLabel(), styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(20, 3, "", styleManager.get(defStyleLabel, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(23, 15, "", styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 7));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 19));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 20, 22));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 23, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 7, Strings.get("doc.physical_table_name"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(8, 12, table.getName(), styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(20, 3, "", styleManager.get(defStyleLabel, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
        cell = createCell(23, 15, "", styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 7));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 19));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 20, 22));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 23, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 37, Strings.get("doc.comment"), styleManager.get(defStyleLabel,
                CellStyle.BORDER_THIN, CellStyle.BORDER_DOTTED, BD_RECT, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 37));

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 37, "", styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, BD_RECT, BD_RECT), row);
        row = sheet.createRow(rowIndex + 1); ///////////////////////////////////////////
        cell = createCell(1, 37, "", styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN,
                CellStyle.BORDER_THIN, BD_RECT, BD_RECT), row);
        row = sheet.createRow(rowIndex + 2); ///////////////////////////////////////////
        cell = createCell(1, 37, "",
                styleManager.get(defStyleHeadValue, CellStyle.BORDER_THIN, BD_RECT, BD_RECT, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex + 2, 1, 37));
        rowIndex += 3;
    }
    ////////////////////////////////////////////////////////////////////////////
    // 
    ////////////////////////////////////////////////////////////////////////////
    {
        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, Strings.get("doc.column_info"), styleTitle, row);

        List<FieldModel> fields = table.getFields();

        short top = BD_RECT;
        short bottom = CellStyle.BORDER_THIN;
        if (0 == fields.size()) {
            bottom = BD_RECT;
        }

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 2, Strings.get("doc.no"),
                styleManager.get(defStyleLabel, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(3, 6, Strings.get("doc.logic_name"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(9, 6, Strings.get("doc.physical_name"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(15, 6, Strings.get("doc.column_type"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(21, 3, Strings.get("doc.not_null"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(24, 3, Strings.get("doc.default_value"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(27, 11, Strings.get("doc.comment"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 3, 8));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 9, 14));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 15, 20));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 21, 23));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 24, 26));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 27, 37));

        IndexModel primaryIndex = table.getPrimaryIndex();

        rowIndex++;
        for (int i = 0; i < fields.size(); i++) {
            int bufRowIndex = rowIndex + i;
            FieldModel field = fields.get(i);

            top = CellStyle.BORDER_DOTTED;
            bottom = CellStyle.BORDER_DOTTED;
            if (i == 0) {
                top = CellStyle.BORDER_THIN;
            }
            if (i + 1 == fields.size()) {
                bottom = BD_RECT;
            }

            XSSFCellStyle defStylePK = defStyleListValue;
            if (null != primaryIndex) {
                if (null != primaryIndex.getField(field.getName())) {
                    defStylePK = defStyleListValuePK;
                }
            }

            String type = field.getType().getLabel();
            if (StringUtility.isNotEmpty(field.getExtra())) {
                type += " " + field.getExtra();
            }

            row = sheet.createRow(bufRowIndex); ///////////////////////////////////////////
            cell = createCell(1, 2, String.format("%d", i + 1),
                    styleManager.get(defStyleListValueNo, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
            cell = createCell(3, 6, field.getLabel(),
                    styleManager.get(defStylePK, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                    row);
            cell = createCell(9, 6, field.getName(),
                    styleManager.get(defStylePK, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                    row);
            cell = createCell(15, 6, type,
                    styleManager.get(defStylePK, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                    row);
            cell = createCell(21, 3, toTrue(field.isNotNull()), styleManager.get(defStyleListValueCenter, top,
                    bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(24, 3, toDefault(field), styleManager.get(defStyleListValue, top, bottom,
                    CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(27, 11, field.getComment(),
                    styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 1, 2));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 3, 8));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 9, 14));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 15, 20));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 21, 23));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 24, 26));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 27, 37));
        }
        rowIndex += fields.size();
    }
    ////////////////////////////////////////////////////////////////////////////
    // 
    ////////////////////////////////////////////////////////////////////////////
    {
        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, Strings.get("doc.index_info"), styleTitle, row);

        List<IndexModel> indexs = table.getIndexs();

        short top = BD_RECT;
        short bottom = CellStyle.BORDER_THIN;
        if (0 == indexs.size()) {
            bottom = BD_RECT;
        }

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 2, Strings.get("doc.no"),
                styleManager.get(defStyleLabel, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(3, 6, Strings.get("doc.index_name"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(9, 12, Strings.get("doc.column_list"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(21, 3, Strings.get("doc.primary_key"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(24, 3, Strings.get("doc.unique_key"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(27, 11, Strings.get("doc.comment"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 3, 8));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 9, 20));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 21, 23));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 24, 26));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 27, 37));

        rowIndex++;
        for (int i = 0; i < indexs.size(); i++) {
            int bufRowIndex = rowIndex + i;
            IndexModel index = indexs.get(i);

            top = CellStyle.BORDER_DOTTED;
            bottom = CellStyle.BORDER_DOTTED;
            if (i == 0) {
                top = CellStyle.BORDER_THIN;
            }
            if (i + 1 == indexs.size()) {
                bottom = BD_RECT;
            }

            row = sheet.createRow(bufRowIndex); ///////////////////////////////////////////
            cell = createCell(1, 2, String.format("%d", i + 1),
                    styleManager.get(defStyleListValueNo, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
            cell = createCell(3, 6, index.getName(), styleManager.get(defStyleListValue, top, bottom,
                    CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(9, 12, toColumnList(index), styleManager.get(defStyleListValue, top, bottom,
                    CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(21, 3, toTrue(index.isPrimaryKey()), styleManager.get(defStyleListValueCenter,
                    top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(24, 3, toTrue(index.isUnique()), styleManager.get(defStyleListValueCenter, top,
                    bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(27, 11, index.getComment(),
                    styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 1, 2));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 3, 8));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 9, 20));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 21, 23));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 24, 26));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 27, 37));
        }
        rowIndex += indexs.size();
    }
    ////////////////////////////////////////////////////////////////////////////
    // 
    ////////////////////////////////////////////////////////////////////////////
    {
        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, Strings.get("doc.foreign_key_info"), styleTitle, row);

        List<ForeignKeyModel> foreignKeys = table.getForeignKeys();

        short top = BD_RECT;
        short bottom = CellStyle.BORDER_THIN;
        if (0 == foreignKeys.size()) {
            bottom = BD_RECT;
        }

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 2, Strings.get("doc.no"),
                styleManager.get(defStyleLabel, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(3, 6, Strings.get("doc.foreign_key_name"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(9, 12, Strings.get("doc.column_list"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(21, 6, Strings.get("doc.ref_table"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(27, 11, Strings.get("doc.ref_column_list"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 3, 8));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 9, 20));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 21, 26));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 27, 37));

        rowIndex++;
        for (int i = 0; i < foreignKeys.size(); i++) {
            int bufRowIndex = rowIndex + i;
            ForeignKeyModel foreignKey = foreignKeys.get(i);

            Hyperlink link = createTableLink(foreignKey.getReferenceTableName());

            top = CellStyle.BORDER_DOTTED;
            bottom = CellStyle.BORDER_DOTTED;
            if (i == 0) {
                top = CellStyle.BORDER_THIN;
            }
            if (i + 1 == foreignKeys.size()) {
                bottom = BD_RECT;
            }

            row = sheet.createRow(bufRowIndex); ///////////////////////////////////////////
            cell = createCell(1, 2, String.format("%d", i + 1),
                    styleManager.get(defStyleListValueNo, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
            cell = createCell(3, 6, foreignKey.getName(), styleManager.get(defStyleListValue, top, bottom,
                    CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(9, 12, toForeignKeyColumnList(foreignKey), styleManager.get(defStyleListValue,
                    top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
            cell = createCell(21, 6, foreignKey.getReferenceTableName(), styleManager.get(defStyleListValueLink,
                    top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), link, row);
            cell = createCell(27, 11, toForeignKeyRefColumnList(foreignKey),
                    styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 1, 2));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 3, 8));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 9, 20));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 21, 26));
            sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 27, 37));
        }
        rowIndex += foreignKeys.size();
    }
    ////////////////////////////////////////////////////////////////////////////
    // (Ref)
    ////////////////////////////////////////////////////////////////////////////
    {
        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, Strings.get("doc.foreign_key_info_ref"), styleTitle, row);

        int size = 0;
        for (TableModel targetTable : datasource.getTables()) {
            if (targetTable.equals(table)) {
                continue;
            }
            List<ForeignKeyModel> foreignKeys = targetTable.getForeignKeys();
            for (ForeignKeyModel foreignKey : foreignKeys) {
                if (!foreignKey.getReferenceTableName().equals(table.getName())) {
                    continue;
                }
                size++;
            }
        }

        short top = BD_RECT;
        short bottom = CellStyle.BORDER_THIN;
        if (0 == size) {
            bottom = BD_RECT;
        }

        rowIndex++;
        row = sheet.createRow(rowIndex); ///////////////////////////////////////////
        cell = createCell(1, 2, Strings.get("doc.no"),
                styleManager.get(defStyleLabel, top, bottom, BD_RECT, CellStyle.BORDER_THIN), row);
        cell = createCell(3, 6, Strings.get("doc.foreign_key_name"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(9, 12, Strings.get("doc.column_list"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(21, 6, Strings.get("doc.ref_former_table"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN),
                row);
        cell = createCell(27, 11, Strings.get("doc.ref_former_column_list"),
                styleManager.get(defStyleLabel, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 3, 8));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 9, 20));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 21, 26));
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 27, 37));

        int cnt = 0;
        rowIndex++;
        for (TableModel targetTable : datasource.getTables()) {
            if (targetTable.equals(table)) {
                continue;
            }

            List<ForeignKeyModel> foreignKeys = targetTable.getForeignKeys();
            for (ForeignKeyModel foreignKey : foreignKeys) {
                if (!foreignKey.getReferenceTableName().equals(table.getName())) {
                    continue;
                }

                int bufRowIndex = rowIndex + cnt;
                Hyperlink link = createTableLink(targetTable.getName());

                top = CellStyle.BORDER_DOTTED;
                bottom = CellStyle.BORDER_DOTTED;
                if (cnt == 0) {
                    top = CellStyle.BORDER_THIN;
                }
                if (cnt + 1 == size) {
                    bottom = BD_RECT;
                }

                row = sheet.createRow(bufRowIndex); ///////////////////////////////////////////
                cell = createCell(1, 2, String.format("%d", cnt + 1),
                        styleManager.get(defStyleListValueNo, top, bottom, BD_RECT, CellStyle.BORDER_THIN),
                        row);
                cell = createCell(3, 6, foreignKey.getName(), styleManager.get(defStyleListValue, top, bottom,
                        CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
                cell = createCell(9, 12, toForeignKeyRefColumnList(foreignKey), styleManager.get(
                        defStyleListValue, top, bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), row);
                cell = createCell(21, 6, targetTable.getName(), styleManager.get(defStyleListValueLink, top,
                        bottom, CellStyle.BORDER_THIN, CellStyle.BORDER_THIN), link, row);
                cell = createCell(27, 11, toForeignKeyColumnList(foreignKey),
                        styleManager.get(defStyleListValue, top, bottom, CellStyle.BORDER_THIN, BD_RECT), row);
                sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 1, 2));
                sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 3, 8));
                sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 9, 20));
                sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 21, 26));
                sheet.addMergedRegion(new CellRangeAddress(bufRowIndex, bufRowIndex, 27, 37));

                cnt++;
            }
        }

        rowIndex += cnt;
    }

    workbook.setPrintArea(workbook.getSheetIndex(getTableSheetName(table.getName())), 0, 38, 0, rowIndex);
    sheet.setAutobreaks(true);
    XSSFPrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setFitWidth((short) 1);
    printSetup.setScale((short) 95);

    return sheet;
}

From source file:org.centralperf.helper.view.ExcelOOXMLView.java

License:Open Source License

/**
 * @see AbstractPOIExcelView#buildExcelDocument(Map, Workbook, HttpServletRequest, HttpServletResponse)
 *//*from  www  .  j a  v  a  2s .c  o m*/
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    log.debug("Generating Excel report from run samples");

    // Set the headers
    response.setHeader("Content-Type", "application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=central_perf_result.xlsx");

    // get data model which is passed by the Spring container
    Run run = (Run) model.get("run");

    // Set run summary informations
    setCellValueByName(PROJECT_NAME_CELL_NAME, run.getProject().getName(), workbook);
    setCellValueByName(RUN_LABEL_CELL_NAME, run.getLabel(), workbook);
    setCellValueByName(RUN_DESCRIPTION_CELL_NAME, run.getComment(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(START_DATE_CELL_NAME, run.getStartDate().toString(), workbook);
    setCellValueByName(GENERATED_ON_CELL_NAME, "" + unixTimestamp2ExcelTimestampconvert(new Date().getTime()),
            workbook);

    // Populate data sheet
    XSSFSheet dataSheet = (XSSFSheet) workbook.getSheet(DATA_SHEET_NAME);
    // Set date style for first column
    CellStyle dateStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy/mm/dd"));
    dataSheet.setDefaultColumnStyle(0, dateStyle);

    // Add samples
    for (int i = 0; i < run.getSamples().size(); i++) {
        Sample sample = run.getSamples().get(i);
        XSSFRow dataRow = dataSheet.createRow(i + 1);
        if (sample.getTimestamp() != null) {
            dataRow.createCell(0)
                    .setCellValue(unixTimestamp2ExcelTimestampconvert(sample.getTimestamp().getTime()));
            dataRow.createCell(1).setCellValue(sample.getElapsed());
            dataRow.createCell(2).setCellValue(sample.getSampleName());
            dataRow.createCell(3).setCellValue(sample.getStatus());
            dataRow.createCell(4).setCellValue(sample.getReturnCode());
            dataRow.createCell(5).setCellValue(sample.getSizeInOctet());
            dataRow.createCell(6).setCellValue(sample.getGrpThreads());
            dataRow.createCell(7).setCellValue(sample.getAllThreads());
            dataRow.createCell(8).setCellValue(sample.getLatency());
        }
    }

    // Return generated sheet
    OutputStream outStream = null;
    try {
        outStream = response.getOutputStream();
        workbook.write(outStream);
        outStream.flush();
    } finally {
        outStream.close();
    }

}

From source file:org.cgiar.ccafs.marlo.action.center.capdev.test.java

License:Open Source License

public void createFile() throws FileNotFoundException {
    try {/*www  .  ja  v  a  2  s.  c  om*/
        DataValidation dataValidationCountries = null;
        DataValidation dataValidationInstitutions = null;
        DataValidation dataValidationCountryOfInstitutions = null;
        DataValidationConstraint constraintCountries = null;
        DataValidationConstraint constraintInstitutions = null;
        DataValidationConstraint constraintCountryOfInstitutions = null;
        DataValidationHelper validationHelper = null;

        final String path = new File(".").getCanonicalPath();
        final String filePath = "C:\\Users\\logonzalez\\Downloads\\participants-template.xlsm";
        final File file = new File(filePath);
        final FileInputStream fileInput = new FileInputStream(file);
        final XSSFWorkbook wb = new XSSFWorkbook(fileInput);

        final Sheet sheet1 = wb.getSheetAt(0);
        final XSSFSheet sheet2 = wb.getSheet("countries");
        final XSSFSheet sheet3 = wb.getSheet("institutions");

        final String reference = null;
        final String dataValidationCountryName = "countriesLis";
        final String dataValidationInstitutionName = "institutionsList";

        final String[] countries = { "1- Colombia", "2- Brazil", "3- Espenia", "4- Argentina", "5- Aruba",
                "6- Egipto", "7- Panama", "8- Ecuador" };
        final String[] institutions = { "CH- U.chile", "BZ- U.coritiba", "PN- U.panama", "AR- U.de.Palermo",
                "AF- U.delNilo", "EC- U.de.Quito", };

        for (int i = 0; i < countries.length; i++) {
            final Row fila = sheet2.createRow(i);
            final Cell celda = fila.createCell(0);
            final Cell celdaformula = fila.createCell(1);
            // final String formula = "SUM(C1,D1)";
            celda.setCellValue(countries[i]);
            // celdaformula.setCellFormula(formula);
        }

        // sheet2.protectSheet("marlo-ciat");
        // // 3. create named range for an area using AreaReference
        // final Name namedCountry = wb.createName();
        // namedCountry.setNameName(dataValidationCountryName);
        // reference = "countries!$A$1:$A$" + countries.length; // area reference
        // namedCountry.setRefersToFormula(reference);

        for (int i = 0; i < institutions.length; i++) {
            final Row fila = sheet3.createRow(i);
            final Cell celda = fila.createCell(0);
            celda.setCellValue(institutions[i]);

        }

        // final Name namedInstitution = wb.createName();
        // namedInstitution.setNameName(dataValidationInstitutionName);
        // reference = "institutions!$A$1:$A$" + institutions.length; // area reference
        // namedInstitution.setRefersToFormula(reference);
        //
        // sheet3.protectSheet("marlo-ciat");

        validationHelper = sheet1.getDataValidationHelper();
        final CellRangeAddressList addressListCountry = new CellRangeAddressList(11, 1000, 4, 4);
        constraintCountries = validationHelper.createFormulaListConstraint(dataValidationCountryName);
        dataValidationCountries = validationHelper.createValidation(constraintCountries, addressListCountry);
        dataValidationCountries.setSuppressDropDownArrow(true);
        if (dataValidationCountries instanceof XSSFDataValidation) {
            dataValidationCountries.setSuppressDropDownArrow(true);
            dataValidationCountries.setShowErrorBox(true);
        } else {
            dataValidationCountries.setSuppressDropDownArrow(false);
        }

        final CellRangeAddressList addressListInstitution = new CellRangeAddressList(11, 1000, 6, 6);
        constraintInstitutions = validationHelper.createFormulaListConstraint(dataValidationInstitutionName);
        dataValidationInstitutions = validationHelper.createValidation(constraintInstitutions,
                addressListInstitution);
        dataValidationInstitutions.setSuppressDropDownArrow(true);
        if (dataValidationInstitutions instanceof XSSFDataValidation) {
            dataValidationInstitutions.setSuppressDropDownArrow(true);
            dataValidationInstitutions.setShowErrorBox(true);
        } else {
            dataValidationInstitutions.setSuppressDropDownArrow(false);
        }

        final CellRangeAddressList addressListCountryOfInstitution = new CellRangeAddressList(11, 1000, 7, 7);
        constraintCountryOfInstitutions = validationHelper
                .createFormulaListConstraint(dataValidationCountryName);
        dataValidationCountryOfInstitutions = validationHelper.createValidation(constraintCountryOfInstitutions,
                addressListCountryOfInstitution);
        dataValidationCountryOfInstitutions.setSuppressDropDownArrow(true);
        if (dataValidationCountryOfInstitutions instanceof XSSFDataValidation) {
            dataValidationCountryOfInstitutions.setSuppressDropDownArrow(true);
            dataValidationCountryOfInstitutions.setShowErrorBox(true);
        } else {
            dataValidationCountryOfInstitutions.setSuppressDropDownArrow(false);
        }

        sheet1.addValidationData(dataValidationCountries);
        sheet1.addValidationData(dataValidationInstitutions);
        sheet1.addValidationData(dataValidationCountryOfInstitutions);

        FileOutputStream fileOut;

        fileOut = new FileOutputStream("C:\\Users\\logonzalez\\Downloads\\vineet.xlsm");
        wb.write(fileOut);
        fileOut.close();
        wb.close();

    } catch (EncryptedDocumentException | IOException e1) {
        e1.printStackTrace();
    }
}

From source file:org.cvrgrid.hl7.fileparse.PicuDataLoader.java

License:Apache License

public static void main(String[] args) throws Exception {

    PicuDataLoader picuDataLoader = new PicuDataLoader();
    SimpleDateFormat fromUser = new SimpleDateFormat("yyyyMMddHHmmss");
    SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    OpenTSDBConfiguration openTSDBConfiguration = picuDataLoader.getOpenTSDBConfiguration();
    String urlString = openTSDBConfiguration.getOpenTSDBUrl();
    HL7Measurements hl7Measurements = new HL7Measurements();
    HashMap<String, String> measurementNames = hl7Measurements.getMeasurementNames();
    XSSFWorkbook wb = readFile(openTSDBConfiguration.getAwareSupportedParams());
    XSSFSheet sheet = wb.getSheetAt(0);/*  ww  w  .  j  a  v  a2s .co  m*/
    for (int r = 1; r < 280; r++) {
        XSSFRow row = sheet.getRow(r);
        if (row == null) {
            continue;
        }
        String key = row.getCell(2).getStringCellValue();
        String value = row.getCell(1).getStringCellValue();
        value = value.replaceAll(":", "/");
        measurementNames.put(key, value);
    }
    HashMap<String, PatientInfo> idMatch = new HashMap<String, PatientInfo>();
    File f = new File(openTSDBConfiguration.getIdMatch());
    if (f.exists()) {
        wb = readFile(openTSDBConfiguration.getIdMatch());
        sheet = wb.getSheetAt(0);
        for (int r = 1; r < sheet.getLastRowNum() + 1; r++) {
            XSSFRow row = sheet.getRow(r);
            PatientInfo patInfo = new PatientInfo();
            patInfo.setPicuSubject(row.getCell(1).getBooleanCellValue());
            patInfo.setFirstName(row.getCell(3).getStringCellValue());
            patInfo.setLastName(row.getCell(4).getStringCellValue());
            patInfo.setBirthDateTime(row.getCell(5).getStringCellValue());
            patInfo.setGender(row.getCell(6).getStringCellValue());
            patInfo.setBirthplace(row.getCell(7).getStringCellValue());
            patInfo.setEarliestDataPoint(row.getCell(8).getStringCellValue());
            LinkedList<String> locations = new LinkedList<String>();
            String lSet = row.getCell(10).getStringCellValue();
            lSet = lSet.replaceAll("\\[", "");
            lSet = lSet.replaceAll("\\]", "");
            String[] locationSet = lSet.split(",");
            for (String location : locationSet) {
                locations.add(location.trim());
            }
            patInfo.setLocations(locations);
            LinkedList<String> variables = new LinkedList<String>();
            String vSet = row.getCell(12).getStringCellValue();
            vSet = vSet.replaceAll("\\[", "");
            vSet = vSet.replaceAll("\\]", "");
            String[] variableSet = vSet.split(",");
            for (String variable : variableSet) {
                variables.add(variable.trim());
            }
            patInfo.setVariables(variables);
            idMatch.put(patInfo.getHash(), patInfo);
        }
    }
    System.out.println("Existing Subject Count: " + idMatch.size());
    String processedFile = openTSDBConfiguration.getProcessedFile();
    String rootDir = openTSDBConfiguration.getRootDir();
    ArrayList<String> processedFiles = new ArrayList<String>();
    File processedFileContents = new File(processedFile);
    getProcessedFiles(processedFileContents, processedFiles);
    ArrayList<String> messageFiles = new ArrayList<String>();
    File rootDirContents = new File(rootDir);
    getDirectoryContents(rootDirContents, processedFiles, messageFiles);
    XSSFWorkbook workbook;
    XSSFSheet sheetOut, sheetOut2;
    if (processedFiles.size() > 1) {
        workbook = readFile(openTSDBConfiguration.getIdMatch());
        sheetOut = workbook.getSheetAt(0);
        sheetOut2 = workbook.getSheetAt(1);
    } else {
        workbook = new XSSFWorkbook();
        sheetOut = workbook.createSheet("idMatch");
        sheetOut2 = workbook.createSheet(openTSDBConfiguration.getIdMatchSheet());
    }
    for (String filePath : messageFiles) {
        System.out.println("     File: " + filePath);
        FileReader reader = new FileReader(filePath);

        Hl7InputStreamMessageIterator iter = new Hl7InputStreamMessageIterator(reader);

        while (iter.hasNext()) {
            HashMap<String, String> tags = new HashMap<String, String>();
            Message next = iter.next();
            ORU_R01 oru = new ORU_R01();
            oru.parse(next.encode());
            PatientInfo patInfo = new PatientInfo();
            if (Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 5, 0, 2, 1) != null)
                patInfo.setFirstName(Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 5, 0, 2, 1).trim());
            if (Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 5, 0, 1, 1) != null)
                patInfo.setLastName(Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 5, 0, 1, 1).trim());
            if (Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 7, 0, 1, 1) != null)
                patInfo.setBirthDateTime(
                        Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 7, 0, 1, 1).trim());
            if (Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 8, 0, 1, 1) != null)
                patInfo.setGender(Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 8, 0, 1, 1).trim());
            if (Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 23, 0, 1, 1) != null)
                patInfo.setBirthplace(Terser.get(oru.getRESPONSE().getPATIENT().getPID(), 23, 0, 1, 1).trim());
            LinkedList<String> locations = new LinkedList<String>();
            LinkedList<String> variables = new LinkedList<String>();
            if (idMatch.get(patInfo.getHash()) != null) {
                patInfo = idMatch.get(patInfo.getHash());
                locations = patInfo.getLocations();
                variables = patInfo.getVariables();
            }
            if (!locations
                    .contains(Terser.get(oru.getRESPONSE().getPATIENT().getVISIT().getPV1(), 3, 0, 1, 1))) {
                locations.add(Terser.get(oru.getRESPONSE().getPATIENT().getVISIT().getPV1(), 3, 0, 1, 1));
                if (locations.peekLast().startsWith("ZB04"))
                    patInfo.setPicuSubject(true);
            }
            tags.put("subjectId", patInfo.getHash());
            String time = Terser.get(oru.getRESPONSE().getORDER_OBSERVATION().getOBR(), 7, 0, 1, 1);
            Date timepoint = fromUser.parse(time);
            String reformattedTime = myFormat.format(timepoint);
            if (patInfo.getEarliestDataPoint().equalsIgnoreCase("")) {
                patInfo.setEarliestDataPoint(reformattedTime);
            }
            List<ORU_R01_OBSERVATION> observations = oru.getRESPONSE().getORDER_OBSERVATION()
                    .getOBSERVATIONAll();
            for (ORU_R01_OBSERVATION observation : observations) {
                String seriesName = Terser.get(observation.getOBX(), 3, 0, 1, 1);
                if (measurementNames.get(seriesName) != null) {
                    seriesName = measurementNames.get(seriesName);
                } else {
                    seriesName = seriesName.replaceFirst("\\d", "#");
                    seriesName = measurementNames.get(seriesName);
                }

                StringBuffer buff = new StringBuffer();

                String[] tokens = seriesName.split(" ");
                for (String i : tokens) {
                    i = i.replaceAll("\\(", "");
                    i = i.replaceAll("\\)", "");
                    buff.append(StringUtils.capitalize(i));
                }

                String measurementValue = Terser.get(observation.getOBX(), 5, 0, 1, 1);
                String units = Terser.get(observation.getOBX(), 6, 0, 1, 1);
                if (units != null) {
                    units = units.replaceAll(":", "");
                    units = units.replaceAll("cm_h2o", "cmH2O");
                    units = units.replaceAll("\\(min/m2\\)", "MinPerMeterSquared");
                    units = units.replaceAll("l", "liters");
                    units = units.replaceAll("mliters", "milliliters");
                    units = units.replaceAll("g.m", "gramMeters");
                    units = units.replaceAll("dyn.sec.cm-5", "dyneSecondsPerQuinticCentimeter");
                    units = units.replaceAll("dyneSecondsPerQuinticCentimeter.m2",
                            "dyneSecondsPerQuinticCentimeterPerMeterSquared");
                    units = units.replaceAll("m2", "MeterSquared");
                    units = units.replaceAll("min", "Min");
                    units = units.replaceAll("/", "Per");
                    units = units.replaceAll("%", "percent");
                    units = units.replaceAll("#", "Count");
                    units = units.replaceAll("celiters", "Celsius");
                    units = units.replaceAll("mm\\(hg\\)", "mmHg");
                } else {
                    units = "percent";
                }
                seriesName = "vitals." + StringUtils.uncapitalize(units);
                seriesName += "." + StringUtils.uncapitalize(buff.toString());
                seriesName = seriesName.trim();
                if (!variables.contains(StringUtils.uncapitalize(buff.toString())))
                    variables.add(StringUtils.uncapitalize(buff.toString()));
                IncomingDataPoint dataPoint = new IncomingDataPoint(seriesName, timepoint.getTime(),
                        measurementValue, tags);
                TimeSeriesStorer.storeTimePoint(urlString, dataPoint);
            }
            patInfo.setLocations(locations);
            patInfo.setVariables(variables);
            idMatch.put(patInfo.getHash(), patInfo);
        }
        System.out.println("     Subject Count: " + idMatch.size());
        int rowNum = 0;
        Set<String> keys = idMatch.keySet();
        TreeSet<String> sortedKeys = new TreeSet<String>(keys);
        for (String key : sortedKeys) {
            XSSFRow row = sheetOut.createRow(rowNum);
            XSSFRow row2 = sheetOut2.createRow(rowNum);
            XSSFCell cell, cell2;
            if (rowNum == 0) {
                cell = row.createCell(0);
                cell.setCellValue("Count");
                cell = row.createCell(1);
                cell.setCellValue("PICU Subject?");
                cell = row.createCell(2);
                cell.setCellValue("Hash");
                cell = row.createCell(3);
                cell.setCellValue("First Name");
                cell = row.createCell(4);
                cell.setCellValue("Last Name");
                cell = row.createCell(5);
                cell.setCellValue("Birth Date/Time");
                cell = row.createCell(6);
                cell.setCellValue("Gender");
                cell = row.createCell(7);
                cell.setCellValue("Birthplace");
                cell = row.createCell(8);
                cell.setCellValue("First Time Point");
                cell = row.createCell(9);
                cell.setCellValue("Location Count");
                cell = row.createCell(10);
                cell.setCellValue("Locations");
                cell = row.createCell(11);
                cell.setCellValue("Variable Count");
                cell = row.createCell(12);
                cell.setCellValue("Variables");
                cell2 = row2.createCell(0);
                cell2.setCellValue("Count");
                cell2 = row2.createCell(1);
                cell2.setCellValue("PICU Subject?");
                cell2 = row2.createCell(2);
                cell2.setCellValue("Hash");
                cell2 = row2.createCell(3);
                cell2.setCellValue("First Name");
                cell2 = row2.createCell(4);
                cell2.setCellValue("Last Name");
                cell2 = row2.createCell(5);
                cell2.setCellValue("Birth Date/Time");
                cell2 = row2.createCell(6);
                cell2.setCellValue("Gender");
                cell2 = row2.createCell(7);
                cell2.setCellValue("Birthplace");
                cell2 = row2.createCell(8);
                cell2.setCellValue("First Time Point");
                cell2 = row2.createCell(9);
                cell2.setCellValue("Location Count");
                cell2 = row2.createCell(10);
                cell2.setCellValue("Locations");
                cell2 = row2.createCell(11);
                cell2.setCellValue("Variable Count");
                cell2 = row2.createCell(12);
                cell2.setCellValue("Variables");
            } else {
                cell = row.createCell(0);
                cell.setCellValue(rowNum);
                cell = row.createCell(1);
                cell.setCellValue(idMatch.get(key).isPicuSubject());
                cell = row.createCell(2);
                cell.setCellValue(key);
                cell = row.createCell(3);
                cell.setCellValue(idMatch.get(key).getFirstName());
                cell = row.createCell(4);
                cell.setCellValue(idMatch.get(key).getLastName());
                cell = row.createCell(5);
                cell.setCellValue(idMatch.get(key).getBirthDateTime());
                cell = row.createCell(6);
                cell.setCellValue(idMatch.get(key).getGender());
                cell = row.createCell(7);
                cell.setCellValue(idMatch.get(key).getBirthplace());
                cell = row.createCell(8);
                cell.setCellValue(idMatch.get(key).getEarliestDataPoint());
                cell = row.createCell(9);
                cell.setCellValue(idMatch.get(key).getLocations().size());
                cell = row.createCell(10);
                cell.setCellValue(idMatch.get(key).getLocations().toString());
                cell = row.createCell(11);
                cell.setCellValue(idMatch.get(key).getVariables().size());
                cell = row.createCell(12);
                cell.setCellValue(idMatch.get(key).getVariables().toString());
                if (idMatch.get(key).isPicuSubject()) {
                    cell2 = row2.createCell(0);
                    cell2.setCellValue(rowNum);
                    cell2 = row2.createCell(1);
                    cell2.setCellValue(idMatch.get(key).isPicuSubject());
                    cell2 = row2.createCell(2);
                    cell2.setCellValue(key);
                    cell2 = row2.createCell(3);
                    cell2.setCellValue(idMatch.get(key).getFirstName());
                    cell2 = row2.createCell(4);
                    cell2.setCellValue(idMatch.get(key).getLastName());
                    cell2 = row2.createCell(5);
                    cell2.setCellValue(idMatch.get(key).getBirthDateTime());
                    cell2 = row2.createCell(6);
                    cell2.setCellValue(idMatch.get(key).getGender());
                    cell2 = row2.createCell(7);
                    cell2.setCellValue(idMatch.get(key).getBirthplace());
                    cell2 = row2.createCell(8);
                    cell2.setCellValue(idMatch.get(key).getEarliestDataPoint());
                    cell2 = row2.createCell(9);
                    cell2.setCellValue(idMatch.get(key).getLocations().size());
                    cell2 = row2.createCell(10);
                    cell2.setCellValue(idMatch.get(key).getLocations().toString());
                    cell2 = row2.createCell(11);
                    cell2.setCellValue(idMatch.get(key).getVariables().size());
                    cell2 = row2.createCell(12);
                    cell2.setCellValue(idMatch.get(key).getVariables().toString());
                }
            }
            rowNum++;
        }
    }

    if (messageFiles.size() > 0) {
        try {

            FileOutputStream out = new FileOutputStream(new File(openTSDBConfiguration.getIdMatch()));
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully...");
            PrintWriter writer = new PrintWriter(rootDir + "done.txt", "UTF-8");
            for (String filePath : processedFiles) {
                writer.println(filePath);
            }
            for (String filePath : messageFiles) {
                writer.println(filePath);
            }
            writer.close();
            System.out.println("done.txt written successfully...");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Nothing new to process...");
    }
}

From source file:org.gaia.gui.reports.ExcelReportExporter.java

License:Open Source License

/**
 * generate file EXCEL/*from   ww w  .j av a2s . c  om*/
 *
 * @param table
 * @param template
 */
public static void generateExcel(SortableTreeTable table, ReportTemplate template) {
    FileOutputStream fileOut = null;
    XSSFWorkbook wb = new XSSFWorkbook();
    try {
        String excelFilename = generateFileName(template);
        fileOut = new FileOutputStream(excelFilename);

        List<TemplateColumnItem> items = ReportBuilder.orderColumns(template.getTemplateColumnItems());
        TemplateColumnItem item;
        int colMax = table.getColumnModel().getColumnCount();
        if (items.size() < colMax) {
            colMax = items.size();
        }

        XSSFSheet bomSheet = (XSSFSheet) wb.createSheet(template.getTemplateName());

        XSSFRow headerRow = (XSSFRow) bomSheet.createRow(0);
        XSSFCellStyle headerStyle = (XSSFCellStyle) wb.createCellStyle();
        Font font = wb.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        font.setFontName("Tahoma");
        headerStyle.setFont(font);
        headerStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
        headerStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        for (int i = 0; i < colMax; i++) {
            XSSFCell cell = (XSSFCell) headerRow.createCell(i);
            cell.setCellType(XSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(table.getColumnName(i));
            cell.setCellStyle(headerStyle);
        }

        XSSFCellStyle cellStyle = (XSSFCellStyle) wb.createCellStyle();

        font = wb.createFont();
        font.setFontName("Tahoma");
        cellStyle.setFont(font);
        cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
        for (int j = 0; j < table.getRowCount(); j++) {
            XSSFRow row = (XSSFRow) bomSheet.createRow(j + 1);
            for (int i = 0; i < colMax; i++) {
                XSSFCell cell = (XSSFCell) row.createCell(i);
                cell.setCellStyle(cellStyle);
                Object value = table.getValueAt(j, i);
                item = (TemplateColumnItem) items.get(i);
                if (value != null && !value.equals(StringUtils.EMPTY_STRING)) {
                    Class<?> clazz = Class.forName(item.getReturnType());

                    //used for Snapshot Export
                    if (clazz == String.class && NumberUtils.isInteger(value.toString())) {
                        clazz = Integer.class;
                    } else if (clazz == String.class && NumberUtils.isNumber(value.toString())) {
                        clazz = BigDecimal.class;
                    }

                    if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(((Short) value).intValue());
                    } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(Integer.parseInt(value.toString()));
                    } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(((Long) value).intValue());
                    } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(((Float) value).doubleValue());
                    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(Double.parseDouble(value.toString()));
                    } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue((Double) value);
                    } else if (Date.class.isAssignableFrom(clazz)) {
                        cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
                        cell.setCellValue(HSSFDateUtil.getExcelDate((java.sql.Date) value));
                    } else {
                        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
                        cell.setCellValue(value.toString());
                    }
                }
            }

        }

        for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
            bomSheet.autoSizeColumn(i);
        }

        SortableTreeTableModel model = (SortableTreeTableModel) table.getTreeTableModel();
        AbstractSortableTreeTableNode root = (AbstractSortableTreeTableNode) model.getRoot();
        groupNode(root, bomSheet);
        wb.write(fileOut);
        fileOut.flush();
        fileOut.close();
        nodeList.clear();
        groupList.clear();
        allNodeList.clear();

        openExcel(excelFilename);
    } catch (ClassNotFoundException | IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        try {
            fileOut.close();
        } catch (IOException ex) {
            logger.error(ex);
        }
    }
}

From source file:org.isatools.isacreatorconfigurator.configui.io.Utils.java

License:Open Source License

public static String createTableConfigurationEXL(String outputDir,
        Map<MappingObject, List<Display>> tableFields)
        throws DataNotCompleteException, InvalidFieldOrderException, IOException {

    String excelFileName = "ISA-config-template.xlsx";
    FileOutputStream fos = new FileOutputStream(outputDir + File.separator + excelFileName);

    String tableName = "";

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet hiddenSheet = workbook.createSheet("hiddenCV");

    Map<String, List<String>> nodups = new HashMap<String, List<String>>();
    XSSFSheet ontologyRestriction = workbook.createSheet("Restrictions");
    XSSFRow ontorow0 = ontologyRestriction.createRow((short) 0);

    ontorow0.createCell(0).setCellValue("Column Name");
    ontorow0.createCell(1).setCellValue("Ontology");
    ontorow0.createCell(2).setCellValue("Branch");
    ontorow0.createCell(3).setCellValue("Version");

    CreationHelper factory = workbook.getCreationHelper();

    //  int counting=0;
    //  int ontocounter=0;
    int lastposition = 0;

    for (MappingObject mo : tableFields.keySet()) {

        tableName = mo.getAssayName().replace("\\s", "");

        List<Display> elements = tableFields.get(mo);

        System.out.println("creating worksheet: " + tableName);

        //we create a table with 50 records by default for anything that is not an investigation file
        if (!tableName.contains("investigation")) {

            XSSFSheet tableSheet = workbook.createSheet(tableName);
            Drawing drawing = tableSheet.createDrawingPatriarch();
            CellStyle style = workbook.createCellStyle();
            XSSFRow rowAtIndex;/*ww w  . j a  v a 2  s  .c om*/

            //we create 51 rows by default for each table
            for (int index = 0; index <= 50; index++) {
                rowAtIndex = tableSheet.createRow((short) index);
            }

            //the first row is the header we need to build from the configuration declaration
            XSSFRow header = tableSheet.getRow(0);

            //we now iterated through the element found in the xml table configuration
            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {

                if (elements.get(fieldIndex).getFieldDetails() != null) {

                    if (elements.get(fieldIndex).getFieldDetails().isRequired() == true) {

                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.RED.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        System.out.println("REQUIRED field number " + fieldIndex + " is: "
                                + elements.get(fieldIndex).getFieldDetails().getFieldName());

                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);

                    } else {
                        XSSFCell cell = header.createCell(fieldIndex);
                        Font font = workbook.createFont();
                        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

                        style.setFont(font);
                        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
                        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
                        font.setColor(IndexedColors.BLACK.index);
                        cell.setCellStyle(style);
                        //create the header field by setting to FieldName as Cell name
                        cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                        //using the ISA field description to create a Comment attached to the set
                        ClientAnchor anchor = factory.createClientAnchor();
                        Comment comment = drawing.createCellComment(anchor);
                        RichTextString rts = factory.createRichTextString(
                                elements.get(fieldIndex).getFieldDetails().getDescription());
                        comment.setString(rts);
                        cell.setCellComment(comment);
                        tableSheet.autoSizeColumn(fieldIndex);
                    }

                    //checking if the field requires controled values, i.e ISA datatype is List

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.LIST) {

                        //create a hidden spreadsheet and named range with the list of val
                        //counting++; //incrementing the counter defining the position where to start the new namedrange in the hidden spreadsheet

                        //obtain the name of the ISA fields and extracting key information needed to create a unique name for the Named Range to be
                        String rangeName = elements.get(fieldIndex).getFieldDetails().getFieldName()
                                .replace("'", "").replace(" ", "").replace("Comment[", "")
                                .replace("ParameterValue[", "").replace("Characteristics[", "").replace("]", "")
                                .replace("(", "").replace(")", "");

                        //getting all the values allowed by the List Field
                        String[] fieldValues = elements.get(fieldIndex).getFieldDetails().getFieldList();

                        //System.out.println("CV : "+elements.get(fieldIndex).getFieldDetails().getFieldName()+ " values: "  + Arrays.asList(fieldValues).toString()+ "size :" +fieldValues.length);

                        //iterating through the values and creating a cell for each
                        for (int j = 0; j < fieldValues.length; j++) {
                            hiddenSheet.createRow(lastposition + j).createCell(0).setCellValue(fieldValues[j]);
                        }

                        Name namedCell = workbook.createName();

                        workbook.getNumberOfNames();

                        int k = 0;
                        int position = 0;

                        //this is to handle ISA Fields sharing the same name (in different assays)
                        //namedRanges in Excel must be unique

                        while (k < workbook.getNumberOfNames()) { //we can the total number of field to type list we have found so far.

                            //something already exists...
                            if (workbook.getNameAt(k).equals(rangeName)) {
                                // namedCell.setNameName(workbook.getNameAt(k).toString());
                                //no need to go further, we exit here and set the parameter position to use the value
                                position = k;
                                k = -1;
                            } else {
                                k++;
                            }
                        }

                        if (k > 0) { //this means this field already existed list of that type
                            //we name the new cell after it
                            namedCell.setNameName(rangeName + k);
                            System.out.println("Name Name: " + namedCell.getNameName());
                        } else { //there is already one, so we just point back to it using the position parameter
                            namedCell.setNameName(workbook.getNameAt(k).toString()); //workbook.getNameAt(position).toString()
                            System.out.println("Name Name: " + namedCell.getNameName());
                        }

                        int start = 0;
                        int end = 0;
                        start = lastposition + 1;
                        System.out.println("start: + " + start);
                        end = lastposition + fieldValues.length;
                        System.out.println("end: + " + end);

                        //                                    String reference ="hiddenCV"+"!"+convertNumToColString(0)+start+":"+ convertNumToColString(0)+end;
                        String reference = "hiddenCV" + "!$" + convertNumToColString(0) + "$" + start + ":$"
                                + convertNumToColString(0) + "$" + end;
                        namedCell.setRefersToFormula(reference);

                        start = 0;
                        end = 0;
                        DataValidationHelper validationHelper = new XSSFDataValidationHelper(tableSheet);
                        DataValidationConstraint constraint = validationHelper
                                .createFormulaListConstraint(reference);
                        CellRangeAddressList addressList = new CellRangeAddressList(1, 50, fieldIndex,
                                fieldIndex);

                        System.out.println("field index: " + fieldIndex);
                        DataValidation dataValidation = validationHelper.createValidation(constraint,
                                addressList);

                        tableSheet.addValidationData(dataValidation);

                        lastposition = lastposition + fieldValues.length;
                        System.out.println("lastposition: + " + lastposition);
                        System.out.println("reference: " + reference);
                    }

                    //                                //TODO: reformat date but this is pain in Excel
                    //                                if (elements.get(fieldIndex).getFieldDetails().getDatatype()== DataTypes.DATE) {
                    //                                    //do something
                    //                                }

                    //  If a default value has been specified in the ISAconfiguration, we set it in the Excel spreadsheet
                    if (elements.get(fieldIndex).getFieldDetails().getDefaultVal() != null) {
                        for (int i = 1; i < 51; i++) {
                            rowAtIndex = tableSheet.getRow(i);
                            XSSFCell cellThere = rowAtIndex.createCell(fieldIndex);
                            cellThere.setCellValue(elements.get(fieldIndex).getFieldDetails().getDefaultVal());
                        }
                    }

                    if (elements.get(fieldIndex).getFieldDetails().getDatatype() == DataTypes.ONTOLOGY_TERM) {
                        int count = elements.get(fieldIndex).getFieldDetails().getRecommmendedOntologySource()
                                .values().size();
                        Collection<RecommendedOntology> myList = elements.get(fieldIndex).getFieldDetails()
                                .getRecommmendedOntologySource().values();
                        for (RecommendedOntology recommendedOntology : myList) {
                            System.out.println("ONTOLOGY :" + recommendedOntology.getOntology());
                            try {
                                if (recommendedOntology.getOntology() != null) {
                                    ArrayList<String> ontoAttributes = new ArrayList<String>();
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyID());
                                    ontoAttributes.add(recommendedOntology.getOntology().getOntologyVersion());
                                    //  ontocounter++;
                                    //                                              XSSFRow ontoRowj = ontologyRestriction.createRow(ontocounter);
                                    //                                              ontoRowj.createCell(0).setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());
                                    //                                              ontoRowj.createCell(1).setCellValue(recommendedOntology.getOntology().getOntologyID());
                                    //                                              ontoRowj.createCell(3).setCellValue(recommendedOntology.getOntology().getOntologyVersion());

                                    if (recommendedOntology.getBranchToSearchUnder() != null) {
                                        System.out.println("ONTOLOGY BRANCH :"
                                                + recommendedOntology.getBranchToSearchUnder());
                                        //                                                  ontoRowj.createCell(2).setCellValue(recommendedOntology.getBranchToSearchUnder().toString());
                                        ontoAttributes
                                                .add(recommendedOntology.getBranchToSearchUnder().toString());
                                    } else {
                                        ontoAttributes.add("");
                                    }

                                    nodups.put(elements.get(fieldIndex).getFieldDetails().getFieldName(),
                                            ontoAttributes);
                                }
                            } catch (NullPointerException npe) {
                                System.out.println(npe);
                            }
                        }
                    }
                }
            }
        } else {

            //we now create with the Investigation Sheet
            XSSFSheet tableSheet = workbook.createSheet(tableName);

            Drawing drawing = tableSheet.createDrawingPatriarch();

            CellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();

            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);

            for (int fieldIndex = 0; fieldIndex < elements.size(); fieldIndex++) {
                XSSFRow row = tableSheet.createRow((short) fieldIndex);
                if (elements.get(fieldIndex).getFieldDetails() != null) {
                    XSSFCell cell = row.createCell(0);
                    //create the header field by setting to FieldName as Cell name
                    cell.setCellValue(elements.get(fieldIndex).getFieldDetails().getFieldName());

                    //using the ISA field description to create a Comment attached to the set
                    ClientAnchor anchor = factory.createClientAnchor();
                    Comment comment = drawing.createCellComment(anchor);
                    RichTextString rts = factory
                            .createRichTextString(elements.get(fieldIndex).getFieldDetails().getDescription());
                    comment.setString(rts);
                    cell.setCellComment(comment);
                    cell.setCellStyle(style);
                    tableSheet.autoSizeColumn(fieldIndex);

                    SheetConditionalFormatting sheetCF = tableSheet.getSheetConditionalFormatting();

                    //condition: if the output of the FIND function is equal to 1, then, set cell to a blue font
                    ConditionalFormattingRule rule = sheetCF
                            .createConditionalFormattingRule("FIND(Investigation,$A$1:$A$21)>1");
                    //ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule(ComparisonOperator.) ;
                    FontFormatting font1 = rule.createFontFormatting();
                    font1.setFontStyle(false, true);
                    font1.setFontColorIndex(IndexedColors.BLUE.index);

                    CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:A21") };

                    sheetCF.addConditionalFormatting(regions, rule);
                }
            }
            tableSheet.setSelected(true);
            workbook.setSheetOrder(tableName, 0);

        }
    }

    //writes the values of ontology resources used to restrict selection in ISA fields
    int compteur = 1;

    for (Map.Entry<String, List<String>> entry : nodups.entrySet()) {
        String key = entry.getKey();
        // Object value = entry.getValue();

        System.out.println("UNIQUE RESOURCE: " + key);
        XSSFRow ontoRowj = ontologyRestriction.createRow(compteur);
        ontoRowj.createCell(0).setCellValue(key);
        ontoRowj.createCell(1).setCellValue(entry.getValue().get(0));
        ontoRowj.createCell(2).setCellValue(entry.getValue().get(2));
        ontoRowj.createCell(3).setCellValue(entry.getValue().get(1));

        compteur++;

    }

    //moving support worksheet to be the rightmost sheets in the workbook.
    //if the table corresponds to the study sample table, we move it to first position
    if (tableName.toLowerCase().contains("studysample")) {
        workbook.setSheetOrder(tableName, 1);
    }
    workbook.setSheetOrder("hiddenCV", tableFields.keySet().size() + 1);
    workbook.setSheetOrder("Restrictions", tableFields.keySet().size() + 1);
    workbook.write(fos);
    fos.close();

    String message = "Files have been saved in ";

    if (outputDir.equals("")) {
        message += "this programs directory";
    } else {
        message += outputDir;
    }

    return message;
}