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

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

Introduction

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

Prototype

Sheet createSheet(String sheetname);

Source Link

Document

Create a new sheet for this Workbook and return the high level representation.

Usage

From source file:com.adobe.acs.commons.mcp.impl.ProcessErrorReportExcelServlet.java

License:Apache License

@SuppressWarnings("squid:S3776")
protected Workbook createSpreadsheet(ManagedProcess report) {
    Workbook wb = new XSSFWorkbook();

    String name = report.getName();
    for (char ch : new char[] { '\\', '/', '*', '[', ']', ':', '?' }) {
        name = StringUtils.remove(name, ch);
    }/* w ww. ja  v  a  2  s. co m*/
    Sheet sheet = wb.createSheet(name);
    sheet.createFreezePane(0, 1, 0, 1);

    Row headerRow = sheet.createRow(0);
    CellStyle headerStyle = createHeaderStyle(wb);
    CellStyle dateStyle = wb.createCellStyle();
    CreationHelper createHelper = wb.getCreationHelper();
    dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyy/mm/dd h:mm:ss"));

    for (String columnName : Arrays.asList("Time", "Path", "Error", "Stack trace")) {
        Cell headerCell = headerRow.createCell(headerRow.getPhysicalNumberOfCells());
        headerCell.setCellValue(columnName);
        headerCell.setCellStyle(headerStyle);
    }

    Collection<ArchivedProcessFailure> rows = report.getReportedErrorsList();
    //make rows, don't forget the header row
    for (ArchivedProcessFailure error : rows) {
        Row row = sheet.createRow(sheet.getPhysicalNumberOfRows());
        Cell c;

        c = row.createCell(0);
        c.setCellValue(error.time);
        c.setCellStyle(dateStyle);
        c = row.createCell(1);
        c.setCellValue(error.nodePath);
        c = row.createCell(2);
        c.setCellValue(error.error);
        c = row.createCell(3);
        c.setCellValue(error.stackTrace);
    }
    autosize(sheet, 4);
    sheet.setAutoFilter(new CellRangeAddress(0, 1 + rows.size(), 0, 3));
    return wb;
}

From source file:com.alibaba.ims.platform.util.ExcelUtil.java

License:Open Source License

private static void write(List<List<String>> rows, File file) throws IOException {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("sheet1");

    for (int i = 0; i < rows.size(); i++) {
        Row row = sheet.createRow(i);/*  w w  w.  ja v  a  2 s.  c  om*/
        for (int j = 0; j < rows.get(i).size(); j++) {
            Cell cell = row.createCell(j);
            cell.setCellValue(rows.get(i).get(j));
        }
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        workbook.write(fos);
    } finally {
        if (fos != null) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.alibaba.stonelab.webxsample.sample.web.module.screen.Download.java

License:Open Source License

private Workbook getWorkbook() {
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("gift");
    Row row = sheet.createRow(0);/*from  w  w w . j av  a 2 s.c  om*/
    row.createCell(0).setCellValue("id");
    row.createCell(1).setCellValue("name");
    for (int i = 1; i <= 10; i++) {
        Row r = sheet.createRow(i);
        r.createCell(0).setCellValue(i);
        r.createCell(1).setCellValue("name" + i);
    }
    return wb;
}

From source file:com.AllenBarr.CallSheetGenerator.Generator.java

License:Open Source License

public int generateSheet(File file, Contributor contrib) {
    //create workbook file
    final String fileName = file.toString();
    final Workbook wb;
    if (fileName.endsWith(".xlsx")) {
        wb = new XSSFWorkbook();
    } else if (fileName.endsWith(".xls")) {
        wb = new HSSFWorkbook();
    } else {/*from www.j  a v  a 2  s .  c  o m*/
        return 1;
    }
    //create sheet
    final Sheet sheet = wb.createSheet("Call Sheet");
    final Header header = sheet.getHeader();
    header.setCenter("Anderson for Iowa Call Sheet");
    //add empty cells
    final Row[] row = new Row[22 + contrib.getDonationsLength()];
    final Cell[][] cell = new Cell[6][22 + contrib.getDonationsLength()];
    for (int i = 0; i < (22 + contrib.getDonationsLength()); i++) {
        row[i] = sheet.createRow((short) i);
        for (int j = 0; j < 6; j++) {
            cell[j][i] = row[i].createCell(j);
        }
    }
    //populate cells with data
    //column 1
    cell[0][0].setCellValue(contrib.getName());
    cell[0][3].setCellValue("Sex:");
    cell[0][4].setCellValue("Party:");
    cell[0][5].setCellValue("Phone #:");
    cell[0][6].setCellValue("Home #:");
    cell[0][7].setCellValue("Cell #:");
    cell[0][8].setCellValue("Work #:");
    cell[0][10].setCellValue("Email:");
    cell[0][12].setCellValue("Employer:");
    cell[0][13].setCellValue("Occupation:");
    cell[0][15].setCellValue("Past Contact:");
    cell[0][17].setCellValue("Notes:");
    cell[0][21].setCellValue("Contribution History:");
    //column 2
    cell[1][3].setCellValue(contrib.getSex());
    cell[1][4].setCellValue(contrib.getParty());
    cell[1][5].setCellValue(contrib.getPhone());
    cell[1][6].setCellValue(contrib.getHomePhone());
    cell[1][7].setCellValue(contrib.getCellPhone());
    cell[1][8].setCellValue(contrib.getWorkPhone());
    cell[1][9].setCellValue("x" + contrib.getWorkExtension());
    cell[1][10].setCellValue(contrib.getEmail());
    cell[1][12].setCellValue(contrib.getEmployer());
    cell[1][13].setCellValue(contrib.getOccupation());
    cell[1][17].setCellValue(contrib.getNotes());
    //column 4
    cell[3][3].setCellValue("Salutation:");
    cell[3][4].setCellValue("Age:");
    cell[3][5].setCellValue("Spouse:");
    cell[3][7].setCellValue("Address:");
    cell[3][10].setCellValue("TARGET:");
    //column 5
    cell[4][0].setCellValue("VANID:");
    cell[4][3].setCellValue(contrib.getSalutation());
    cell[4][4].setCellValue(contrib.getAge());
    cell[4][5].setCellValue(contrib.getSpouse());
    cell[4][7].setCellValue(contrib.getStreetAddress());
    cell[4][8].setCellValue(contrib.getCity() + ", " + contrib.getState() + " " + contrib.getZip());
    //column 6
    cell[5][0].setCellValue(contrib.getVANID());
    //contribution cells
    for (int i = 0; i < contrib.getDonationsLength(); i++) {
        cell[0][i + 22].setCellValue(contrib.getDonation(i).getDonationDate());
        cell[1][i + 22].setCellValue(contrib.getDonation(i).getRecipient());
        cell[5][i + 22].setCellValue(contrib.getDonation(i).getAmount());
    }

    //format cells
    //Name cell
    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
    final CellStyle leftBoldUnderline14Style = wb.createCellStyle();
    final Font boldUnderline14Font = wb.createFont();
    boldUnderline14Font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldUnderline14Font.setUnderline(Font.U_SINGLE);
    boldUnderline14Font.setFontHeightInPoints((short) 14);
    boldUnderline14Font.setFontName("Garamond");
    leftBoldUnderline14Style.setFont(boldUnderline14Font);
    leftBoldUnderline14Style.setAlignment(CellStyle.ALIGN_LEFT);
    cell[0][0].setCellStyle(leftBoldUnderline14Style);
    //field name cells
    final CellStyle rightBold10Style = wb.createCellStyle();
    final Font bold10Font = wb.createFont();
    bold10Font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    bold10Font.setFontHeightInPoints((short) 10);
    bold10Font.setFontName("Garamond");
    rightBold10Style.setFont(bold10Font);
    rightBold10Style.setAlignment(CellStyle.ALIGN_RIGHT);
    for (int i = 3; i < 22; i++) {
        cell[0][i].setCellStyle(rightBold10Style);
    }
    sheet.addMergedRegion(new CellRangeAddress(21, 21, 0, 1));
    for (int i = 3; i < 11; i++) {
        cell[3][i].setCellStyle(rightBold10Style);
    }
    cell[4][0].setCellStyle(rightBold10Style);
    //field content cells
    final CellStyle left10Style = wb.createCellStyle();
    final Font garamond10Font = wb.createFont();
    garamond10Font.setFontHeightInPoints((short) 10);
    garamond10Font.setFontName("Garamond");
    left10Style.setFont(garamond10Font);
    left10Style.setAlignment(CellStyle.ALIGN_LEFT);
    for (int i = 3; i < 5; i++) {
        cell[1][i].setCellStyle(left10Style);
    }
    //phone number cells
    final CellStyle phoneStyle = wb.createCellStyle();
    phoneStyle.setFont(garamond10Font);
    phoneStyle.setAlignment(CellStyle.ALIGN_LEFT);
    final CreationHelper createHelper = wb.getCreationHelper();
    phoneStyle.setDataFormat(createHelper.createDataFormat().getFormat("[<=9999999]###-####;(###) ###-####"));
    for (int i = 5; i < 9; i++) {
        cell[1][i].setCellStyle(phoneStyle);
        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 2));

    }
    cell[1][9].setCellStyle(left10Style);
    //email through past contact
    for (int i = 10; i < 16; i++) {
        cell[1][i].setCellStyle(left10Style);
    }
    //notes
    CellStyle noteStyle = wb.createCellStyle();
    noteStyle.cloneStyleFrom(left10Style);
    noteStyle.setWrapText(true);
    cell[1][17].setCellStyle(noteStyle);
    //column E
    for (int i = 3; i < 11; i++) {
        cell[4][i].setCellStyle(left10Style);
    }
    //VanID Cell
    final CellStyle right10Style = wb.createCellStyle();
    right10Style.setFont(garamond10Font);
    right10Style.setAlignment(CellStyle.ALIGN_RIGHT);
    cell[5][0].setCellStyle(right10Style);
    //Notes cell
    sheet.addMergedRegion(new CellRangeAddress(17, 19, 1, 5));
    //contribution cells
    final CellStyle date10Style = wb.createCellStyle();
    date10Style.setFont(garamond10Font);
    date10Style.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy"));
    date10Style.setBorderBottom(CellStyle.BORDER_THIN);
    date10Style.setBorderTop(CellStyle.BORDER_THIN);
    date10Style.setBorderLeft(CellStyle.BORDER_THIN);
    date10Style.setBorderRight(CellStyle.BORDER_THIN);
    final CellStyle contributionStyle = wb.createCellStyle();
    contributionStyle.cloneStyleFrom(left10Style);
    contributionStyle.setBorderBottom(CellStyle.BORDER_THIN);
    contributionStyle.setBorderTop(CellStyle.BORDER_THIN);
    contributionStyle.setBorderLeft(CellStyle.BORDER_THIN);
    contributionStyle.setBorderRight(CellStyle.BORDER_THIN);
    final CellStyle money10Style = wb.createCellStyle();
    money10Style.setFont(garamond10Font);
    money10Style.setDataFormat(
            createHelper.createDataFormat().getFormat("_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)"));
    money10Style.setBorderBottom(CellStyle.BORDER_THIN);
    money10Style.setBorderTop(CellStyle.BORDER_THIN);
    money10Style.setBorderLeft(CellStyle.BORDER_THIN);
    money10Style.setBorderRight(CellStyle.BORDER_THIN);
    for (int i = 22; i < 22 + contrib.getDonationsLength(); i++) {
        cell[0][i].setCellStyle(date10Style);
        cell[1][i].setCellStyle(contributionStyle);
        cell[2][i].setCellStyle(contributionStyle);
        cell[3][i].setCellStyle(contributionStyle);
        cell[4][i].setCellStyle(contributionStyle);
        sheet.addMergedRegion(new CellRangeAddress(i, i, 1, 4));
        cell[5][i].setCellStyle(money10Style);

    }
    //resize columns
    sheet.autoSizeColumn(0);
    sheet.autoSizeColumn(1);
    try {
        FileOutputStream fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
    } catch (FileNotFoundException e) {
        return 1;
    } catch (IOException ex) {
        return 1;
    }

    return 0;
}

From source file:com.alvexcore.repo.documents.generation.ExportDataListToXlsx.java

License:Open Source License

protected Workbook createXlsx(JSONArray rows, String XLS_SHEET_NAME) {

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet(XLS_SHEET_NAME);

    for (int k = 0; k < rows.size(); k++) {
        Row row = sheet.createRow((short) k);
        JSONArray cells = (JSONArray) rows.get(k);
        for (int c = 0; c < cells.size(); c++) {
            String displayValue;//from  www.  j av a 2s . c o  m
            Object item = cells.get(c);
            if (item == null)
                displayValue = I18NUtil.getMessage("label.empty");
            else if (item instanceof Boolean)
                displayValue = (Boolean) item ? I18NUtil.getMessage("label.yes")
                        : I18NUtil.getMessage("label.no");
            else
                displayValue = item.toString();
            row.createCell(c).setCellValue(createHelper.createRichTextString(displayValue));
        }
    }

    return wb;
}

From source file:com.alvexcore.repo.documents.generation.ExportReportToXlsx.java

License:Open Source License

protected Workbook createXlsx(JSONArray rows, String XLS_SHEET_NAME) {

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet(XLS_SHEET_NAME);

    for (int k = 0; k < rows.size(); k++) {
        Row row = sheet.createRow((short) k);
        JSONArray cells = (JSONArray) rows.get(k);
        row.createCell(0).setCellValue(createHelper.createRichTextString((String) cells.get(0)));
        for (int c = 1; c < cells.size(); c++)
            row.createCell(c).setCellValue((String) cells.get(c));
    }/*from  www .  j a v  a2s. com*/

    return wb;
}

From source file:com.asakusafw.testdriver.excel.ExcelSheetSinkFactory.java

License:Apache License

@Override
public <T> DataModelSink createSink(DataModelDefinition<T> definition, TestContext context) throws IOException {
    if (definition == null) {
        throw new IllegalArgumentException("definition must not be null"); //$NON-NLS-1$
    }/*from   w w  w . j a va  2  s.  c  om*/
    if (context == null) {
        throw new IllegalArgumentException("context must not be null"); //$NON-NLS-1$
    }

    SpreadsheetVersion version = Util.getSpreadsheetVersionFor(output.getPath());
    if (definition.getProperties().size() > version.getMaxColumns()) {
        LOG.warn(MessageFormat.format(Messages.getString("ExcelSheetSinkFactory.warnExceedColumnCount"), //$NON-NLS-1$
                definition.getModelClass().getName(), version.getMaxColumns(), output));
    }
    File parent = output.getParentFile();
    if (parent != null && parent.isDirectory() == false && parent.mkdirs() == false) {
        throw new IOException(MessageFormat.format(
                Messages.getString("ExcelSheetSinkFactory.errorFailedToCreateOutputDirectory"), //$NON-NLS-1$
                output));
    }
    final Workbook workbook = Util.createEmptyWorkbookFor(output.getPath());
    Sheet sheet = workbook.createSheet("results"); //$NON-NLS-1$
    return new ExcelSheetSink(definition, sheet, version.getMaxColumns()) {
        private boolean closed = false;

        @Override
        public void close() throws IOException {
            if (closed) {
                return;
            }
            closed = true;
            LOG.info(MessageFormat.format(Messages.getString("ExcelSheetSinkFactory.infoStartOutput"), //$NON-NLS-1$
                    output));
            try (OutputStream stream = new FileOutputStream(output);) {
                workbook.write(stream);
            }
        }
    };
}

From source file:com.automaster.autoview.server.servlet.ExcelServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /*response.setContentType("application/vnd.ms-excel");
     response.setHeader("Content-Disposition", "attachment; filename=filename.xls");
     HSSFWorkbook workbook = new HSSFWorkbook();
     // .../*from   www. j a v  a 2 s .c o m*/
     // Now populate workbook the usual way.
     // ...
     OutputStream arqSaida = response.getOutputStream();
     workbook.write(arqSaida); // Write workbook to response.
     arqSaida.flush();
     arqSaida.close();*/
    //getServletContext().getRealPath("/")
    String tempoDecorrido = " 0";
    String url = getServletContext().getRealPath("/");
    String placa = request.getParameter("placa");
    //TimeZone timeZoneMundial = TimeZone.getTimeZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC));
    Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
    Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));
    //String timeZoneInterface = request.getParameter("timeZone");
    /*String timeZone = "Z";
    if(timeZoneInterface.equalsIgnoreCase("0")){
    timeZone = "Z";
    } else {
    timeZone = String.valueOf((-1) * (Integer.parseInt(timeZoneInterface) / 60));
    }  */
    TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
    System.out.println("Time zone Cliente : " + timeZonePadrao);
    //System.out.println("timeZoneInterface: "+timeZoneInterface);
    //System.out.println("timeZone: "+timeZone);
    //String ign = request.getParameter("ign");
    ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
    ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO.buscarPosicoesPorIntervaloData(placa,
            dataInicio, dataFim);

    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".xlsx");

    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("Histrico - " + placa);
    int pictureIdx;
    try ( //add picture data to this workbook.
            InputStream is = new FileInputStream(url + "/imagens/logo.jpg")) {
        byte[] bytes = IOUtils.toByteArray(is);
        pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
    }

    CreationHelper helper = wb.getCreationHelper();

    // Create the drawing patriarch.  This is the top level container for all shapes. 
    Drawing drawing = sheet.createDrawingPatriarch();

    //add a picture shape
    ClientAnchor anchor = helper.createClientAnchor();
    //set top-left corner of the picture,
    //subsequent call of Picture#resize() will operate relative to it
    anchor.setCol1(1);
    anchor.setRow1(0);
    Picture pict = drawing.createPicture(anchor, pictureIdx);
    //auto-size picture relative to its top-left corner
    pict.resize(3, 3);
    //pict.resize();
    //sheet.setColumnWidth(0, 200);

    Font fonte = wb.createFont();
    fonte.setFontHeightInPoints((short) 24);
    fonte.setFontName("Arial");
    fonte.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    fonte.setItalic(true);
    CellStyle estiloTitulo = wb.createCellStyle();
    estiloTitulo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloTitulo.setFont(fonte);

    Font fonteCabecalho = wb.createFont();
    fonteCabecalho.setFontHeightInPoints((short) 14);
    fonteCabecalho.setFontName("Arial");
    fonteCabecalho.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
    //fonteCabecalho.setItalic(true);
    CellStyle estiloCabecalho = wb.createCellStyle();
    estiloCabecalho.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estiloCabecalho.setFont(fonteCabecalho);

    Font fonteTituloTabela = wb.createFont();
    //fonteTituloTabela.setFontHeightInPoints((short) 14);
    fonteTituloTabela.setFontName("Arial");
    fonteTituloTabela.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

    CellStyle estilo = wb.createCellStyle();
    estilo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    estilo.setFont(fonteTituloTabela);

    CellStyle estiloCorpo = wb.createCellStyle();
    estiloCorpo.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    //estiloCorpo.setFillBackgroundColor(HSSFColor.WHITE.index);
    //estiloCorpo.setFont(fonteTituloTabela);

    XSSFRow linha6 = (XSSFRow) sheet.createRow(6);
    XSSFCell cell046 = linha6.createCell(3);
    cell046.setCellValue("Relatrio de Posies");
    cell046.setCellStyle(estiloTitulo);
    //sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 3));

    XSSFRow linha7 = (XSSFRow) sheet.createRow(7);
    XSSFCell cell047 = linha7.createCell(3);
    cell047.setCellValue("Veculo : " + placa);
    cell047.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(7, 7, 0, 3));

    XSSFRow linha8 = (XSSFRow) sheet.createRow(8);
    XSSFCell cell038 = linha8.createCell(3);
    //TimeZone.setDefault(timeZoneMundial);
    //Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
    //TimeZone.setDefault(timeZoneCliente);
    //Date dataHoraInicio = new Date(dataHoraInicio0.getTime());
    SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    dataFormatadaCabecalho.setTimeZone(timeZonePadrao);
    cell038.setCellValue("Perodo: De: " + dataFormatadaCabecalho.format(dataInicio) + " at: "
            + dataFormatadaCabecalho.format(dataFim));
    cell038.setCellStyle(estiloCabecalho);
    //sheet.addMergedRegion(new CellRangeAddress(8, 8, 0, 3));

    sheet.setColumnWidth(0, 5000);
    sheet.setColumnWidth(1, 3000);
    sheet.setColumnWidth(2, 3500);
    //sheet.setColumnWidth(3, 4000);
    sheet.setColumnWidth(3, 30000);
    //sheet.setColumnWidth(4, 4000);
    //sheet.setColumnWidth(4, 30000);
    sheet.setColumnWidth(5, 3000);
    sheet.setColumnWidth(6, 3000);
    sheet.setColumnWidth(7, 3000);
    sheet.setColumnWidth(8, 3000);
    sheet.setColumnWidth(9, 3000);
    //sheet.setColumnWidth(10, 20000);        
    sheet.setColumnWidth(11, 3000);
    XSSFRow linha9 = (XSSFRow) sheet.createRow(10);
    XSSFCell cell0 = linha9.createCell(0);
    cell0.setCellValue("Data e hora");
    cell0.setCellStyle(estilo);
    XSSFCell cell1 = linha9.createCell(1);
    cell1.setCellValue("Velocidade");
    cell1.setCellStyle(estilo);
    XSSFCell cell2 = linha9.createCell(2);
    cell2.setCellValue("Ignio");
    cell2.setCellStyle(estilo);
    //XSSFCell cell3 = linha9.createCell(3);
    //cell3.setCellValue("Latitude");
    //cell3.setCellStyle(estilo);
    //XSSFCell cell4 = linha9.createCell(4);
    //cell4.setCellValue("Longitude");
    //cell4.setCellStyle(estilo);
    //XSSFCell cell5 = linha9.createCell(5);
    //cell5.setCellValue("Satlite");
    //cell5.setCellStyle(estilo);
    //XSSFCell cell6 = linha9.createCell(6);
    //cell6.setCellValue("GPS");
    //cell6.setCellStyle(estilo);
    //XSSFCell cell7 = linha9.createCell(7);
    //cell7.setCellValue("Entrada");
    //cell7.setCellStyle(estilo);
    //XSSFCell cell8 = linha9.createCell(8);
    //cell8.setCellValue("Sada");
    //cell8.setCellStyle(estilo);
    //XSSFCell cell9 = linha9.createCell(9);
    //cell9.setCellValue("Evento");
    //cell9.setCellStyle(estilo);
    XSSFCell cell10 = linha9.createCell(3);
    cell10.setCellValue("Endereo");
    cell10.setCellStyle(estilo);
    //sheet.addMergedRegion(new CellRangeAddress(11, 11, 4, 8));
    //XSSFCell cell11 = linha9.createCell(11);
    //cell11.setCellValue("Direo");
    //cell11.setCellStyle(estilo);
    int linha = 0;
    int j = 11;
    double latAnt = 0;
    double lonAnt = 0;
    double latAtual = 0;
    double lonAtual = 0;
    double distancia = 0;
    double distanciaTotal = 0;
    for (int i = 0; i < posicoes.size(); i++) {
        XSSFRow row = (XSSFRow) sheet.createRow(j);
        if (i == 0) {
            distancia = 0;
            //System.out.println("linha 00 - EXCEL");
        } else {
            //System.out.println("linha 01 - EXCEL");
            latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
            latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
            lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
            //System.out.println("linha 02 - PDF");
            if (latAnt == latAtual && lonAnt == lonAtual) {
                distancia = 0;
            } else {
                distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                //System.out.println("linha 03 - PDF");
            }

        }
        distanciaTotal = distanciaTotal + distancia;
        /*if(i==0) {
         latAnt = Double.parseDouble(posicoes.get(i).get("lat"));
         lonAnt = Double.parseDouble(posicoes.get(i).get("lon"));
        } else{
            latAnt = Double.parseDouble(posicoes.get(i-1).get("lat"));
            lonAnt = Double.parseDouble(posicoes.get(i-1).get("lon"));
        }
        double latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
        double lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
        double distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
        distanciaTotal = distanciaTotal + distancia;*/
        for (int col = 0; col < posicoes.get(linha).size(); col++) {
            XSSFCell cell = row.createCell(col);
            cell.setCellStyle(estiloCorpo);
            switch (col) {
            case 0:
                Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
                Date dataHora = new Date(dataHora0.getTime());
                SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                dataFormatada.setTimeZone(timeZonePadrao);
                cell.setCellValue(dataFormatada.format(dataHora));
                break;
            case 1:
                cell.setCellValue(posicoes.get(linha).get("vel"));
                break;
            case 2:
                cell.setCellValue(
                        posicoes.get(linha).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada");
                break;
            /*case 3:
                cell.setCellValue(posicoes.get(linha).get("lat"));
                break;
            case 4:
                cell.setCellValue(posicoes.get(linha).get("lon"));
                break;
            case 5:
                cell.setCellValue(posicoes.get(linha).get("sat"));
                break;
            case 6:
                cell.setCellValue(posicoes.get(linha).get("gps"));
                break;
            case 7:
                cell.setCellValue(posicoes.get(linha).get("entrada"));
                break;
            case 8:
                cell.setCellValue(posicoes.get(linha).get("saida"));
                break;
            case 9:
                cell.setCellValue(posicoes.get(linha).get("evento"));
                break;*/
            case 3:
                cell.setCellValue(posicoes.get(linha).get("endereco") == null ? "Sem endereo"
                        : posicoes.get(linha).get("endereco"));
                break;
            /*case 11:
                cell.setCellValue(posicoes.get(linha).get("direcao"));
                break;*/
            }

        }
        j = j + 1;
        linha = linha + 1;

    }
    tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
            Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
    int index = 0;
    String kms = "0";
    String m = "";
    double metros = 0;
    if (distanciaTotal > 0) {
        BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
        index = String.valueOf(decimalFormatado).indexOf(".");
        kms = String.valueOf(decimalFormatado).substring(0, index);
        m = "0" + (String.valueOf(decimalFormatado).substring(index));
        metros = Double.parseDouble(m) * 1000;
    }
    //String formatted = NumberFormat.getFormat("000.00").format(metros);
    //System.out.println("Percorridos aproximadamente : "+kms+" KM e "+metros+" metros");
    XSSFRow linhaX = (XSSFRow) sheet.createRow(linha + 12);
    XSSFCell cellX = linhaX.createCell(0);
    sheet.addMergedRegion(new CellRangeAddress(linha + 12, linha + 12, 0, 3));
    cellX.setCellStyle(estilo);
    cellX.setCellValue(
            "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido);
    ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
    wb.write(outByteStream);

    byte[] outArray = outByteStream.toByteArray();
    OutputStream outStream = response.getOutputStream();
    outStream.write(outArray);
    outStream.flush();

}

From source file:com.automaster.autoview.server.servlet.TesteImagemPOI.java

public static void main(String[] args) throws FileNotFoundException, IOException {

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("new sheet");
    byte data[] = new byte[8000];
    try {// w  w  w.  j  a  v  a2s.  c om
        new DataInputStream(new FileInputStream(
                "D:\\Users\\Adriano\\Documents\\NetBeansProjects\\JRGWT\\web\\imagens\\logo.jpg")).read(data);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    int index = wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG);

    HSSFClientAnchor ancora = new HSSFClientAnchor(0, 0, 0, 0, (short) 0, 5, (short) 10, 10);
    ancora.setAnchorType(2);
    sheet.createDrawingPatriarch().createPicture(ancora, index);

    //Write the Excel file
    FileOutputStream fileOut = null;
    fileOut = new FileOutputStream("C://myFile.xls");
    wb.write(fileOut);
    fileOut.close();

}

From source file:com.b510.excel.client.BusinessPlan.java

License:Apache License

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

    if (args.length > 0 && args[0].equals("-xls"))
        wb = new HSSFWorkbook();
    else/*  ww  w.java  2 s  .  co  m*/
        wb = new XSSFWorkbook();

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

    Sheet sheet = wb.createSheet("Business Plan");

    //turn off gridlines
    sheet.setDisplayGridlines(false);
    sheet.setPrintGridlines(false);
    sheet.setFitToPage(true);
    sheet.setHorizontallyCenter(true);
    PrintSetup printSetup = sheet.getPrintSetup();
    printSetup.setLandscape(true);

    //the following three statements are required only for HSSF
    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    //the header row: centered text in 48pt font
    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);
    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell(i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));
    }
    //columns for 11 weeks starting from 9-Jul
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);

    calendar.setTime(fmt.parse("9-Jul"));
    calendar.set(Calendar.YEAR, year);
    for (int i = 0; i < 11; i++) {
        Cell cell = headerRow.createCell(titles.length + i);
        cell.setCellValue(calendar);
        cell.setCellStyle(styles.get("header_date"));
        calendar.roll(Calendar.WEEK_OF_YEAR, true);
    }
    //freeze the first row
    sheet.createFreezePane(0, 1);

    Row row;
    Cell cell;
    int rownum = 1;
    for (int i = 0; i < data.length; i++, rownum++) {
        row = sheet.createRow(rownum);
        if (data[i] == null)
            continue;

        for (int j = 0; j < data[i].length; j++) {
            cell = row.createCell(j);
            String styleName;
            boolean isHeader = i == 0 || data[i - 1] == null;
            switch (j) {
            case 0:
                if (isHeader) {
                    styleName = "cell_b";
                    cell.setCellValue(Double.parseDouble(data[i][j]));
                } else {
                    styleName = "cell_normal";
                    cell.setCellValue(data[i][j]);
                }
                break;
            case 1:
                if (isHeader) {
                    styleName = i == 0 ? "cell_h" : "cell_bb";
                } else {
                    styleName = "cell_indented";
                }
                cell.setCellValue(data[i][j]);
                break;
            case 2:
                styleName = isHeader ? "cell_b" : "cell_normal";
                cell.setCellValue(data[i][j]);
                break;
            case 3:
                styleName = isHeader ? "cell_b_centered" : "cell_normal_centered";
                cell.setCellValue(Integer.parseInt(data[i][j]));
                break;
            case 4: {
                calendar.setTime(fmt.parse(data[i][j]));
                calendar.set(Calendar.YEAR, year);
                cell.setCellValue(calendar);
                styleName = isHeader ? "cell_b_date" : "cell_normal_date";
                break;
            }
            case 5: {
                int r = rownum + 1;
                String fmla = "IF(AND(D" + r + ",E" + r + "),E" + r + "+D" + r + ",\"\")";
                cell.setCellFormula(fmla);
                styleName = isHeader ? "cell_bg" : "cell_g";
                break;
            }
            default:
                styleName = data[i][j] != null ? "cell_blue" : "cell_normal";
            }

            cell.setCellStyle(styles.get(styleName));
        }
    }

    //group rows for each phase, row numbers are 0-based
    sheet.groupRow(4, 6);
    sheet.groupRow(9, 13);
    sheet.groupRow(16, 18);

    //set column widths, the width is measured in units of 1/256th of a character width
    sheet.setColumnWidth(0, 256 * 6);
    sheet.setColumnWidth(1, 256 * 33);
    sheet.setColumnWidth(2, 256 * 20);
    sheet.setZoom(3, 4);

    // Write the output to a file
    String file = "businessplan.xls";
    if (wb instanceof XSSFWorkbook)
        file += "x";
    FileOutputStream out = new FileOutputStream(file);
    wb.write(out);
    out.close();
}