Example usage for org.apache.poi.ss.usermodel Workbook getCreationHelper

List of usage examples for org.apache.poi.ss.usermodel Workbook getCreationHelper

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel Workbook getCreationHelper.

Prototype

CreationHelper getCreationHelper();

Source Link

Document

Returns an object that handles instantiating concrete classes of the various instances one needs for HSSF and XSSF.

Usage

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

License:Open Source License

/**
 * @see AbstractPOIExcelView#buildExcelDocument(Map, Workbook, HttpServletRequest, HttpServletResponse)
 *///from   w w w.  java2s. c om
@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.datanucleus.store.excel.ExcelPersistenceHandler.java

License:Open Source License

/**
 * Method to insert the object into the datastore.
 * @param op ObjectProvider of the object
 *//*  w  ww .  j  a v a  2  s .  c om*/
public void insertObject(final ObjectProvider op) {
    // Check if read-only so update not permitted
    assertReadOnlyForUpdateOfObject(op);

    AbstractClassMetaData cmd = op.getClassMetaData();
    ExecutionContext ec = op.getExecutionContext();
    ManagedConnection mconn = storeMgr.getConnection(ec);
    try {
        long startTime = System.currentTimeMillis();
        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST.debug(
                    Localiser.msg("Excel.Insert.Start", op.getObjectAsPrintable(), op.getInternalObjectId()));
        }

        Workbook wb = (Workbook) mconn.getConnection();
        if (!storeMgr.managesClass(cmd.getFullClassName())) {
            // Make sure schema exists, using this connection
            ((ExcelStoreManager) storeMgr).manageClasses(new String[] { cmd.getFullClassName() },
                    ec.getClassLoaderResolver(), wb);
        }
        Table table = ec.getStoreManager().getStoreDataForClass(cmd.getFullClassName()).getTable();

        if (cmd.getIdentityType() == IdentityType.APPLICATION
                || cmd.getIdentityType() == IdentityType.DATASTORE) {
            // Enforce uniqueness of datastore rows
            try {
                locateObject(op);
                throw new NucleusUserException(Localiser.msg("Excel.Insert.ObjectWithIdAlreadyExists",
                        op.getObjectAsPrintable(), op.getInternalObjectId()));
            } catch (NucleusObjectNotFoundException onfe) {
                // Do nothing since object with this id doesn't exist
            }
        }

        int[] fieldNumbers = cmd.getAllMemberPositions();
        String sheetName = table.getName();
        Sheet sheet = wb.getSheet(sheetName);
        int rowNum = 0;
        if (sheet == null) {
            // Sheet doesn't exist so create it
            sheet = wb.createSheet(sheetName);
            if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                NucleusLogger.DATASTORE_PERSIST.debug(
                        Localiser.msg("Excel.Insert.SheetCreated", op.getObjectAsPrintable(), sheetName));
            }
        } else {
            // Find number of active rows in this sheet
            rowNum += ExcelUtils.getNumberOfRowsInSheetOfWorkbook(op, wb);
        }

        // Create the object in the datastore
        Row row = sheet.getRow(rowNum);
        if (row == null) {
            // No row present so create holder for the cells
            row = sheet.createRow(rowNum);
        }

        op.provideFields(fieldNumbers, new StoreFieldManager(op, row, true, table));

        if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
            NucleusLogger.DATASTORE_PERSIST
                    .debug(Localiser.msg("Excel.ExecutionTime", (System.currentTimeMillis() - startTime)));
        }
        if (ec.getStatistics() != null) {
            ec.getStatistics().incrementNumWrites();
            ec.getStatistics().incrementInsertCount();
        }

        if (cmd.getIdentityType() == IdentityType.DATASTORE) {
            // Set the datastore identity column value
            int idCellNum = table.getDatastoreIdColumn().getPosition();
            Object key = IdentityUtils.getTargetKeyForDatastoreIdentity(op.getInternalObjectId());
            Cell idCell = row.getCell(idCellNum);
            if (idCell == null) {
                idCell = row.createCell(idCellNum);
            }
            if (key instanceof String) {
                idCell.setCellValue(wb.getCreationHelper().createRichTextString((String) key));
            } else {
                idCell.setCellValue(((Long) key).longValue());
            }
        }

        VersionMetaData vermd = cmd.getVersionMetaDataForClass();
        if (vermd != null) {
            // versioned object so set its version
            int verCellNum = table.getVersionColumn().getPosition();
            Cell verCell = row.getCell(verCellNum);
            if (verCell == null) {
                verCell = row.createCell(verCellNum);
            }

            Object nextVersion = VersionHelper.getNextVersion(vermd.getVersionStrategy(), null);
            op.setTransactionalVersion(nextVersion);
            if (nextVersion instanceof Long) {
                if (NucleusLogger.DATASTORE.isDebugEnabled()) {
                    NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersistedWithVersion",
                            op.getObjectAsPrintable(), op.getInternalObjectId(), "" + nextVersion));
                }
                verCell.setCellValue((Long) nextVersion);
            } else if (nextVersion instanceof Timestamp) {
                if (NucleusLogger.DATASTORE.isDebugEnabled()) {
                    NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersistedWithVersion",
                            op.getObjectAsPrintable(), op.getInternalObjectId(), "" + nextVersion));
                }
                Date date = new Date();
                date.setTime(((Timestamp) nextVersion).getTime());
                verCell.setCellValue(date);
            }
        } else {
            if (NucleusLogger.DATASTORE.isDebugEnabled()) {
                NucleusLogger.DATASTORE.debug(Localiser.msg("Excel.Insert.ObjectPersisted",
                        op.getObjectAsPrintable(), op.getInternalObjectId()));
            }
        }
    } finally {
        mconn.release();
    }
}

From source file:org.dhatim.fastexcel.Benchmarks.java

License:Apache License

private int poiPopulate(org.apache.poi.ss.usermodel.Workbook wb) throws Exception {
    Sheet ws = wb.createSheet("Sheet 1");
    CellStyle dateStyle = wb.createCellStyle();
    dateStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
    for (int r = 0; r < NB_ROWS; ++r) {
        Row row = ws.createRow(r);//from   w ww .ja v  a  2  s.c o  m
        row.createCell(0).setCellValue(r);
        row.createCell(1).setCellValue(Integer.toString(r % 1000));
        row.createCell(2).setCellValue(r / 87.0);
        Cell c = row.createCell(3);
        c.setCellStyle(dateStyle);
        c.setCellValue(new Date(1549915044));
    }
    CountingOutputStream count = new CountingOutputStream(new NullOutputStream());
    wb.write(count);
    return count.getCount();
}

From source file:org.eclipse.emfforms.internal.spreadsheet.core.renderer.EMFFormsSpreadsheetControlRenderer.java

License:Open Source License

private Comment createComment(Workbook workbook, Sheet sheet, VDomainModelReference domainModelReference,
        int row, int column) throws IOException {
    final CreationHelper factory = workbook.getCreationHelper();

    // When the comment box is visible, have it show in a 1x3 space
    final ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(column);/*www.  j  a v  a2  s  .  co m*/
    anchor.setCol2(column + 1);
    anchor.setRow1(row);
    anchor.setRow2(row + 1);

    final Drawing drawing = sheet.createDrawingPatriarch();
    final Comment comment = drawing.createCellComment(anchor);

    comment.setAuthor("EMFForms Spreadsheet Renderer"); //$NON-NLS-1$
    comment.setVisible(false);
    comment.setString(factory.createRichTextString(getSerializedDMR(domainModelReference)));
    return comment;
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

@Test
public void testDeleteDMRCellCommentValue() throws IOException {
    /* setup *//*from   w  ww  .j  a  va2  s .co  m*/
    stream = bundle.getEntry("errorSheets/basexls").openStream(); //$NON-NLS-1$
    final Workbook workbook = new HSSFWorkbook(stream);
    final Sheet sheet = workbook.getSheetAt(0);
    sheet.getRow(0).getCell(1).getCellComment()
            .setString(workbook.getCreationHelper().createRichTextString("")); //$NON-NLS-1$

    /* act */
    final SpreadsheetImportResult result = EMFFormsSpreadsheetImporter.INSTANCE.importSpreadsheet(workbook,
            eClass);
    final EList<ErrorReport> errorReports = result.getErrorReports();

    /* assert */
    assertEquals(1, errorReports.size());
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

private Comment createComment(Workbook workbook, Sheet sheet, int row, int column) throws IOException {
    final CreationHelper factory = workbook.getCreationHelper();

    // When the comment box is visible, have it show in a 1x3 space
    final ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(column);//  www.jav  a2s  .c  o m
    anchor.setCol2(column + 1);
    anchor.setRow1(row);
    anchor.setRow2(row + 1);

    final Drawing drawing = sheet.createDrawingPatriarch();
    final Comment comment = drawing.createCellComment(anchor);

    comment.setAuthor("EMFForms Spreadsheet Renderer"); //$NON-NLS-1$
    comment.setVisible(false);
    comment.setString(factory.createRichTextString("Ignore Sheet")); //$NON-NLS-1$
    return comment;
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

@Test
public void testBrokenDMR() throws IOException {
    /* setup *///from   w  w  w  . j  a  va2  s  .co m
    stream = bundle.getEntry("errorSheets/basexls").openStream(); //$NON-NLS-1$
    final Workbook workbook = new HSSFWorkbook(stream);
    final Sheet sheet = workbook.getSheetAt(0);
    sheet.getRow(0).getCell(1).getCellComment()
            .setString(workbook.getCreationHelper().createRichTextString("foo")); //$NON-NLS-1$

    /* act */
    final SpreadsheetImportResult result = EMFFormsSpreadsheetImporter.INSTANCE.importSpreadsheet(workbook,
            eClass);
    final EList<ErrorReport> errorReports = result.getErrorReports();

    /* assert */
    assertEquals(1, errorReports.size());
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

@Test
public void testUnresolveableDMR() throws IOException {
    /* setup *///w w  w . jav a2 s  .c om
    stream = bundle.getEntry("errorSheets/basexls").openStream(); //$NON-NLS-1$
    final Workbook workbook = new HSSFWorkbook(stream);
    final Sheet sheet = workbook.getSheetAt(0);
    final String dmrForTaskName = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //$NON-NLS-1$
            "<org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ecore=\"http://www.eclipse.org/emf/2002/Ecore\" xmlns:org.eclipse.emf.ecp.view.model=\"http://org/eclipse/emf/ecp/view/model/170/\">\n" //$NON-NLS-1$
            + "<domainModelEFeature xsi:type=\"ecore:EAttribute\" href=\"http://eclipse/org/emf/ecp/makeithappen/model/task#//User/firstName\"/>\n" //$NON-NLS-1$
            + "<domainModelEReferencePath href=\"http://eclipse/org/emf/ecp/makeithappen/model/task#//Task/assignee\"/>\n" //$NON-NLS-1$
            + "</org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference>\n" + ""; //$NON-NLS-1$ //$NON-NLS-2$
    sheet.getRow(0).getCell(1).getCellComment()
            .setString(workbook.getCreationHelper().createRichTextString(dmrForTaskName));

    /* act */
    final SpreadsheetImportResult result = EMFFormsSpreadsheetImporter.INSTANCE.importSpreadsheet(workbook,
            eClass);
    final EList<ErrorReport> errorReports = result.getErrorReports();

    /* assert */
    assertEquals(1, errorReports.size());
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

@Test
public void testNoObjectIdColumn() throws IOException {
    /* setup *//*ww  w .j a  va 2 s. c  o m*/
    final Workbook workbook = new HSSFWorkbook();
    final Sheet sheet = workbook.createSheet("root"); //$NON-NLS-1$
    final Row rowLabel = sheet.createRow(0);
    rowLabel.createCell(0).setCellValue("My feature"); //$NON-NLS-1$

    final CreationHelper factory = workbook.getCreationHelper();

    // When the comment box is visible, have it show in a 1x3 space
    final ClientAnchor anchor = factory.createClientAnchor();
    anchor.setCol1(0);
    anchor.setCol2(1);
    anchor.setRow1(0);
    anchor.setRow2(1);

    final Drawing drawing = sheet.createDrawingPatriarch();
    final Comment comment = drawing.createCellComment(anchor);
    comment.setString(factory.createRichTextString(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ecore=\"http://www.eclipse.org/emf/2002/Ecore\" xmlns:org.eclipse.emf.ecp.view.model=\"http://org/eclipse/emf/ecp/view/model/170\"><domainModelEFeature xsi:type=\"ecore:EAttribute\" href=\"http://eclipse/org/emf/ecp/makeithappen/model/task#//User/lastName\"/></org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference>")); //$NON-NLS-1$

    final Row rowDescription = sheet.createRow(1);
    rowDescription.createCell(0).setCellValue("My feature description"); //$NON-NLS-1$

    final Row rowMeta = sheet.createRow(2);
    rowMeta.createCell(0).setCellValue("Enter Numbers"); //$NON-NLS-1$

    final Row rowData = sheet.createRow(3);
    rowData.createCell(0).setCellValue("My Feature Value"); //$NON-NLS-1$
    /* act */
    final SpreadsheetImportResult result = EMFFormsSpreadsheetImporter.INSTANCE.importSpreadsheet(workbook,
            eClass);
    assertEquals(1, result.getErrorReports().size());
}

From source file:org.eclipse.emfforms.spreadsheet.integrationtest.ImportErrors_ITest.java

License:Open Source License

@Test
public void testDMRThatNeedsMigration() throws IOException {
    /* setup *//*w  ww  .  java2 s  .  c  o m*/
    stream = bundle.getEntry("errorSheets/basexls").openStream(); //$NON-NLS-1$
    final Workbook workbook = new HSSFWorkbook(stream);

    final CreationHelper factory = workbook.getCreationHelper();
    final Sheet sheet = workbook.getSheetAt(0);
    final RichTextString dmr = factory.createRichTextString(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ecore=\"http://www.eclipse.org/emf/2002/Ecore\" xmlns:org.eclipse.emf.ecp.view.model=\"http://org/eclipse/emf/ecp/view/model\"><domainModelEFeature xsi:type=\"ecore:EAttribute\" href=\"http://eclipse/org/emf/ecp/makeithappen/model/task#//User/lastName\"/></org.eclipse.emf.ecp.view.model:FeaturePathDomainModelReference>"); //$NON-NLS-1$

    sheet.getRow(0).getCell(1).getCellComment().setString(dmr);

    /* act */
    final SpreadsheetImportResult result = EMFFormsSpreadsheetImporter.INSTANCE.importSpreadsheet(workbook,
            eClass);
    final EList<ErrorReport> errorReports = result.getErrorReports();

    /* assert */
    assertEquals(0, errorReports.size());
}