Example usage for org.apache.poi.ss.usermodel Sheet setColumnWidth

List of usage examples for org.apache.poi.ss.usermodel Sheet setColumnWidth

Introduction

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

Prototype

void setColumnWidth(int columnIndex, int width);

Source Link

Document

Set the width (in units of 1/256th of a character width)

The maximum column width for an individual cell is 255 characters.

Usage

From source file:Compras.avanceSurtido.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
     // TODO add your handling code here:
     h = new Herramientas(this.user, 0);
     h.session(sessionPrograma);//from   w  w w .j a  v  a  2s  . c  o  m
     File archivoXLS = null;
     javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
     jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
     String ruta = null;
     if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
         ruta = jF1.getSelectedFile().getAbsolutePath();
         if (ruta != null) {
             archivoXLS = new File(ruta + ".xls");
             try {
                 if (archivoXLS.exists())
                     archivoXLS.delete();
                 archivoXLS.createNewFile();
                 Workbook libro = new HSSFWorkbook();
                 FileOutputStream archivo = new FileOutputStream(archivoXLS);
                 Sheet hoja = libro.createSheet("Avance de pedidos");
                 Font font = libro.createFont();
                 font.setFontHeightInPoints((short) 24);
                 font.setFontName("Arial");
                 font.setItalic(false);
                 font.setBold(true);

                 // Fonts are set into a style so create a new one to use.
                 CellStyle style = libro.createCellStyle();
                 style.setFont(font);

                 Session session = HibernateUtil.getSessionFactory().openSession();
                 session.beginTransaction().begin();
                 Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(orden));

                 Configuracion con = (Configuracion) session.get(Configuracion.class, 1);
                 hoja.setColumnWidth(2, 15000);
                 Row r0 = hoja.createRow(0);
                 Cell celdaTitulo = r0.createCell(0);
                 celdaTitulo.setCellValue(con.getEmpresa());
                 celdaTitulo.setCellStyle(style);

                 Row r1 = hoja.createRow(1);
                 r1.createCell(6).setCellValue("Orden de Taller:");
                 r1.createCell(7).setCellValue(orden);

                 Row r2 = hoja.createRow(2);
                 r2.createCell(0).setCellValue("Marca:");
                 r2.createCell(1).setCellValue(ord.getMarca().getMarcaNombre());
                 r2.createCell(6).setCellValue("N Serie:");
                 r2.createCell(7).setCellValue(ord.getNoSerie());

                 Row r3 = hoja.createRow(3);
                 r3.createCell(0).setCellValue("Tipo:");
                 r3.createCell(1).setCellValue(ord.getTipo().getTipoNombre());
                 r3.createCell(6).setCellValue("N Motor:");
                 r3.createCell(7).setCellValue(ord.getNoMotor());

                 Row r4 = hoja.createRow(4);
                 r4.createCell(0).setCellValue("Modelo:");
                 r4.createCell(1).setCellValue("" + ord.getModelo());

                 hoja.createRow(5).createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************");

                 Row r6 = hoja.createRow(6);
                 r6.createCell(0).setCellValue("Partida");
                 r6.createCell(1).setCellValue("sub");
                 r6.createCell(2).setCellValue("Descripcion");
                 r6.createCell(3).setCellValue("Hoj");
                 r6.createCell(4).setCellValue("Mec");
                 r6.createCell(5).setCellValue("Sus");
                 r6.createCell(6).setCellValue("Ele");
                 r6.createCell(7).setCellValue("Can");
                 r6.createCell(8).setCellValue("Med");
                 r6.createCell(9).setCellValue("Folio");
                 r6.createCell(10).setCellValue("Codigo");
                 r6.createCell(11).setCellValue("Origen");
                 r6.createCell(12).setCellValue("Proveedor");
                 r6.createCell(13).setCellValue("Cant C.");
                 r6.createCell(14).setCellValue("C/U Comprado");
                 r6.createCell(15).setCellValue("Plazo");
                 r6.createCell(16).setCellValue("Pedido");
                 r6.createCell(17).setCellValue("F. Pedido");
                 r6.createCell(18).setCellValue("Entradas");
                 r6.createCell(19).setCellValue("Devoluciones");
                 r6.createCell(20).setCellValue("Pendientes");
                 r6.createCell(21).setCellValue("No Factura");

                 hoja.createRow(7).createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************************************************************************************************************************************************");

                 session.close();
                 if (t_datos.getRowCount() > 0) {
                     for (int i = 0; i < t_datos.getRowCount(); i++) {

                         Row fila = hoja.createRow(i + 8);
                         for (int j = 1; j < t_datos.getColumnCount(); j++) {
                             if (j > 3 && j < 8) {
                                 if ((boolean) t_datos.getValueAt(i, j) == true)
                                     fila.createCell(j - 1).setCellValue("");
                                 else
                                     fila.createCell(j - 1).setCellValue("");
                             } else {
                                 if (t_datos.getValueAt(i, j) != null)
                                     fila.createCell(j - 1).setCellValue("" + t_datos.getValueAt(i, j));
                                 else
                                     fila.createCell(j - 1).setCellValue("");
                             }
                         }
                     }
                 }

                 libro.write(archivo);
                 archivo.close();
                 Desktop.getDesktop().open(archivoXLS);
             } catch (Exception e) {
                 System.out.println(e);
                 e.printStackTrace();
                 JOptionPane.showMessageDialog(this,
                         "No se pudo realizar el reporte si el archivo esta abierto");
             }
         }
     }
 }

From source file:Compras.generaCotizacion.java

void exel() {
     h = new Herramientas(this.user, 0);
     h.session(sessionPrograma);/*w w w.j ava2s . com*/
     javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
     jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
     String ruta = null;
     if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
         ruta = jF1.getSelectedFile().getAbsolutePath();
         if (ruta != null) {
             if (ruta.endsWith(".xls") == true)
                 archivoXLS = new File(ruta);
             else
                 archivoXLS = new File(ruta + ".xls");
             try {
                 if (archivoXLS.exists())
                     archivoXLS.delete();
                 archivoXLS.createNewFile();
                 Workbook libro = new HSSFWorkbook();
                 FileOutputStream archivo = new FileOutputStream(archivoXLS);
                 Sheet hoja = libro.createSheet("Cotizacion");
                 Font font = libro.createFont();
                 font.setFontHeightInPoints((short) 24);
                 font.setFontName("Arial");
                 font.setItalic(false);
                 font.setBold(true);

                 Font font10 = libro.createFont();
                 font10.setFontHeightInPoints((short) 10);
                 font10.setFontName("Arial");
                 font10.setItalic(false);
                 font10.setBold(false);
                 font10.setColor(new HSSFColor.YELLOW().getIndex());

                 Font font11 = libro.createFont();
                 font11.setFontHeightInPoints((short) 10);
                 font11.setFontName("Arial");
                 font10.setItalic(false);
                 font10.setBold(false);
                 font11.setColor(new HSSFColor.BLACK().getIndex());

                 // Fonts are set into a style so create a new one to use.
                 CellStyle style = libro.createCellStyle();
                 CellStyle desBloqueo = libro.createCellStyle();
                 CellStyle desBloqueo1 = libro.createCellStyle();
                 CellStyle desBloqueoFecha = libro.createCellStyle();

                 style.setFont(font);

                 desBloqueo.setFont(font10);
                 desBloqueo.setLocked(false);
                 desBloqueo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                 desBloqueo.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());

                 desBloqueo1.setFont(font11);
                 desBloqueo1.setLocked(false);
                 desBloqueo1.setFillBackgroundColor(new HSSFColor.WHITE().getIndex());

                 desBloqueoFecha.setFont(font10);
                 desBloqueoFecha.setLocked(false);
                 desBloqueoFecha.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
                 desBloqueoFecha.setFillBackgroundColor(new HSSFColor.GREEN().getIndex());
                 desBloqueoFecha.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));

                 Session session = HibernateUtil.getSessionFactory().openSession();
                 session.beginTransaction().begin();
                 Orden ord = (Orden) session.get(Orden.class, Integer.parseInt(orden));
                 Configuracion con = (Configuracion) session.get(Configuracion.class, 1);

                 hoja.setColumnWidth(5, 15000);
                 Row r0 = hoja.createRow(0);
                 Cell celdaTitulo = r0.createCell(0);
                 celdaTitulo.setCellValue(con.getEmpresa());
                 celdaTitulo.setCellStyle(style);

                 Row r1 = hoja.createRow(1);
                 r1.createCell(6).setCellValue("Orden de Taller:");
                 r1.createCell(7).setCellValue(orden);

                 Row r2 = hoja.createRow(2);
                 r2.createCell(0).setCellValue("Marca:");
                 r2.createCell(1).setCellValue(ord.getMarca().getMarcaNombre());
                 r2.createCell(6).setCellValue("N Serie:");
                 r2.createCell(7).setCellValue(ord.getNoSerie());

                 Row r3 = hoja.createRow(3);
                 r3.createCell(0).setCellValue("Tipo:");
                 r3.createCell(1).setCellValue(ord.getTipo().getTipoNombre());
                 r3.createCell(6).setCellValue("N Motor:");
                 r3.createCell(7).setCellValue(ord.getNoMotor());

                 Row r4 = hoja.createRow(4);
                 r4.createCell(0).setCellValue("NP:");
                 r4.createCell(1).setCellValue(t_datos1.getValueAt(t_datos1.getSelectedRow(), 1).toString());
                 r4.createCell(2).setCellValue("Proveedor:");
                 r4.createCell(3).setCellValue(t_datos1.getValueAt(t_datos1.getSelectedRow(), 2).toString());
                 r4.createCell(6).setCellValue("Modelo:");
                 r4.createCell(7).setCellValue("" + ord.getModelo());

                 Row r5 = hoja.createRow(5);
                 r5.createCell(0).setCellValue(
                         "**********************************************************************************[Nota:  Solo puedes editar las celdas de color]*******************************************************************************");

                 Row r6 = hoja.createRow(6);
                 r6.createCell(0).setCellValue("Partida");
                 r6.createCell(1).setCellValue("sub");
                 r6.createCell(2).setCellValue("Cantidad");
                 r6.createCell(3).setCellValue("U/Medida");
                 r6.createCell(4).setCellValue("N Parte");
                 r6.createCell(5).setCellValue("Descripcion");
                 r6.createCell(6).setCellValue("Instruccin");
                 r6.createCell(7).setCellValue("Precio c/u");
                 r6.createCell(8).setCellValue("T o t a l");
                 r6.createCell(9).setCellValue("Origen");
                 r6.createCell(10).setCellValue("Pazo");

                 Row r7 = hoja.createRow(7);
                 r7.createCell(0).setCellValue(
                         "**********************************************************************************************************************************************************************************************************************");

                 List misCotizaciones = null;

                 Query query = session.createQuery("SELECT DISTINCT par FROM Partida par "
                         + "RIGHT JOIN FETCH par.partidaCotizacions partC " + "RIGHT JOIN partC.cotizacion cot "
                         + "where cot.idCotizacion="
                         + t_datos1.getValueAt(t_datos1.getSelectedRow(), 0).toString()
                         + " order by par.idEvaluacion asc, par.subPartida asc");
                 //misCotizaciones=c.addOrder(Order.asc("idCotizacion")).list();
                 misCotizaciones = query.list();

                 if (misCotizaciones.size() > 0) {

                     for (int i = 0; i < misCotizaciones.size(); i++) {
                         Partida Part = (Partida) misCotizaciones.get(i);
                         Row fila = hoja.createRow(i + 8);

                         fila.createCell(0).setCellValue(Part.getIdEvaluacion());
                         fila.createCell(1).setCellValue(Part.getSubPartida());
                         fila.createCell(2).setCellValue(Part.getCant());
                         fila.createCell(3).setCellValue(Part.getMed());

                         Cell aux = fila.createCell(4);
                         aux.setCellStyle(desBloqueo);
                         if (Part.getEjemplar() != null)
                             aux.setCellValue(Part.getEjemplar().getIdParte());
                         else
                             aux.setCellValue("");

                         fila.createCell(5).setCellValue(Part.getCatalogo().getNombre());
                         int fil = i + 9;
                         Cell a10 = fila.createCell(6);
                         a10.setCellStyle(desBloqueo1);
                         a10.setCellValue(Part.getInstruccion());

                         Cell a6 = fila.createCell(7);
                         a6.setCellStyle(desBloqueo);
                         a6.setCellValue("");
                         Cell celForm = fila.createCell(8);
                         celForm.setCellType(HSSFCell.CELL_TYPE_FORMULA);
                         celForm.setCellFormula("H" + fil + "*C" + fil);

                         if (Part.isOri() == true)
                             fila.createCell(9).setCellValue("Ori");
                         else if (Part.isNal() == true)
                             fila.createCell(9).setCellValue("Nal");
                         else if (Part.isDesm() == true)
                             fila.createCell(9).setCellValue("Des");
                         else
                             fila.createCell(9).setCellValue("");
                         Cell a9 = fila.createCell(10);
                         a9.setCellValue("");
                         a9.setCellStyle(desBloqueo);
                     }
                 }

                 hoja.protectSheet("04650077");
                 libro.write(archivo);
                 archivo.close();
                 Desktop.getDesktop().open(archivoXLS);
                 if (session != null)
                     if (session.isOpen())
                         session.close();
             } catch (Exception e) {
                 System.out.println(e);
                 e.printStackTrace();
                 JOptionPane.showMessageDialog(this,
                         "No se pudo realizar el reporte si el archivo esta abierto");
             }
         }
     }
 }

From source file:containerMath.containerMath.java

private void writeOutput(List<Item> rightItems, Sheet sheet, int lastRow) {
    sheet.setColumnWidth(0, 13000);
    this.lastRow = lastRow;
    int j = 0;//from www .j  a va2  s. co m
    Row row1 = sheet.createRow(0);//creating headings
    Cell name = row1.createCell(0);
    name.setCellValue("?");
    Cell quantity = row1.createCell(1);
    quantity.setCellValue("?");
    Cell inPacks = row1.createCell(2);
    inPacks.setCellValue("?  ");
    Cell numOfPacks = row1.createCell(3);
    numOfPacks.setCellValue("? ");
    Cell weightOfPack = row1.createCell(4);
    weightOfPack.setCellValue("? ");
    Cell weightPacks = row1.createCell(5);
    weightPacks.setCellValue(" ?");
    Cell volumeOfPack = row1.createCell(6);
    volumeOfPack.setCellValue(" ");
    Cell volumeOfPacks = row1.createCell(7);
    volumeOfPack.setCellValue(" ");
    for (int i = 0; i < rightItems.size(); i++) {
        Row rowN = sheet.createRow(lastRow + i);
        Cell nameN = rowN.createCell(0);
        nameN.setCellValue(rightItems.get(i).getName());
        Cell quantityN = rowN.createCell(1);
        quantityN.setCellValue(rightItems.get(i).getNumOfItems());
        Cell inPacksN = rowN.createCell(2);
        inPacksN.setCellValue(rightItems.get(i).getItemsInPack());
        Cell numOfPacksN = rowN.createCell(3);
        numOfPacksN.setCellValue(rightItems.get(i).getNumOfPacks());
        Cell weightOfPackN = rowN.createCell(4);
        weightOfPackN.setCellValue(rightItems.get(i).getWeightOfPack());
        Cell weightPacksN = rowN.createCell(5);
        weightPacksN.setCellValue(rightItems.get(i).getSumWeight());
        Cell volumeOfPackN = rowN.createCell(6);
        volumeOfPackN.setCellValue(rightItems.get(i).getVolumeOfPack());
        Cell volumeOfPacksN = rowN.createCell(7);
        volumeOfPacksN.setCellValue(rightItems.get(i).getSumVolume());
        j = lastRow + i;
    }
    Row secondHeadings = sheet.createRow(j + 2); //Headings
    Cell cellFinal = secondHeadings.createCell(0);
    cellFinal.setCellValue("");
    Cell cellWeight = secondHeadings.createCell(5);
    cellWeight.setCellValue(" ?");
    Cell cellVolume = secondHeadings.createCell(7);
    cellVolume.setCellValue(" ");
    Row sumData = sheet.createRow(j + 3);
    Cell cellFinalWeight = sumData.createCell(5);
    cellFinalWeight.setCellValue(sumWeight);
    Cell cellFinalVolume = sumData.createCell(7);
    cellFinalVolume.setCellValue(sumVolume);
    Row rest = sheet.createRow(j + 4); //row for rest space in the container
    Cell restFinal = rest.createCell(0);
    restFinal.setCellValue("?");
    Cell restWeight = rest.createCell(5);
    restWeight.setCellValue("?, ");
    Cell restVolume = rest.createCell(7);
    restVolume.setCellValue("?, 3");
    Row restNumbers = sheet.createRow(j + 5);
    Cell restWeightNumber = restNumbers.createCell(5);
    restWeightNumber.setCellValue(weightLeft);
    Cell restVolumeNumber = restNumbers.createCell(7);
    restVolumeNumber.setCellValue(volumeLeft);
}

From source file:contestTabulation.Setup.java

License:Open Source License

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Entity contestInfo = Retrieve.contestInfo();

    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setTransport(httpTransport)
            .setClientSecrets((String) contestInfo.getProperty("OAuth2ClientId"),
                    (String) contestInfo.getProperty("OAuth2ClientSecret"))
            .build().setFromTokenResponse(new JacksonFactory().fromString(
                    ((Text) contestInfo.getProperty("OAuth2Token")).getValue(), GoogleTokenResponse.class));

    String docName = null, docLevel = null;
    for (Level level : Level.values()) {
        docName = req.getParameter("doc" + level.getName());
        if (docName != null) {
            docLevel = level.toString();
            break;
        }//from   w  w  w  .  j av  a  2  s. c o m
    }

    if (docLevel == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Spreadsheet creation request must have paramater document name parameter set");
        return;
    }

    Query query = new Query("registration")
            .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, docLevel))
            .addSort("schoolName", SortDirection.ASCENDING);
    List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    Map<String, List<JSONObject>> studentData = new HashMap<String, List<JSONObject>>();
    for (Entity registration : registrations) {
        String regSchoolName = ((String) registration.getProperty("schoolName")).trim();
        String regStudentDataJSON = unescapeHtml4(((Text) registration.getProperty("studentData")).getValue());

        JSONArray regStudentData = null;
        try {
            regStudentData = new JSONArray(regStudentDataJSON);
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        for (int i = 0; i < regStudentData.length(); i++) {
            if (!studentData.containsKey(regSchoolName)) {
                studentData.put(regSchoolName, new ArrayList<JSONObject>());
            }
            try {
                studentData.get(regSchoolName).add(regStudentData.getJSONObject(i));
            } catch (JSONException e) {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e.printStackTrace();
                return;
            }
        }
    }

    for (List<JSONObject> students : studentData.values()) {
        Collections.sort(students, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                try {
                    return a.getString("name").compareTo(b.getString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }

    Workbook workbook = new XSSFWorkbook();

    XSSFCellStyle boldStyle = (XSSFCellStyle) workbook.createCellStyle();
    Font boldFont = workbook.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldStyle.setFont(boldFont);

    Map<Subject, XSSFCellStyle> subjectCellStyles = new HashMap<Subject, XSSFCellStyle>();
    for (Subject subject : Subject.values()) {
        final double ALPHA = .144;
        String colorStr = (String) contestInfo.getProperty("color" + subject.getName());
        byte[] backgroundColor = new byte[] { Integer.valueOf(colorStr.substring(1, 3), 16).byteValue(),
                Integer.valueOf(colorStr.substring(3, 5), 16).byteValue(),
                Integer.valueOf(colorStr.substring(5, 7), 16).byteValue() };
        // http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
        byte[] borderColor = new byte[] { (byte) ((backgroundColor[0] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[1] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[2] & 0xff) * (1 - ALPHA)) };

        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        style.setFillBackgroundColor(new XSSFColor(backgroundColor));
        style.setFillPattern(CellStyle.ALIGN_FILL);

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(new XSSFColor(borderColor));
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(new XSSFColor(borderColor));
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(new XSSFColor(borderColor));
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(new XSSFColor(borderColor));
        subjectCellStyles.put(subject, style);
    }

    Entry<String, List<JSONObject>>[] studentDataEntries = studentData.entrySet().toArray(new Entry[] {});
    Arrays.sort(studentDataEntries, Collections.reverseOrder(new Comparator<Entry<String, List<JSONObject>>>() {
        @Override
        public int compare(Entry<String, List<JSONObject>> arg0, Entry<String, List<JSONObject>> arg1) {
            return Integer.compare(arg0.getValue().size(), arg1.getValue().size());
        }
    }));

    for (Entry<String, List<JSONObject>> studentDataEntry : studentDataEntries) {
        Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(studentDataEntry.getKey()));
        Row row = sheet.createRow((short) 0);

        String[] columnNames = { "Name", "Grade", "N", "C", "M", "S" };
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            Cell cell = row.createCell(i);
            cell.setCellValue(columnName);
            cell.setCellStyle(boldStyle);
            CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);
        }

        int longestNameLength = 7;
        int rowNum = 1;
        for (JSONObject student : studentDataEntry.getValue()) {
            try {
                row = sheet.createRow((short) rowNum);
                row.createCell(0).setCellValue(student.getString("name"));
                row.createCell(1).setCellValue(student.getInt("grade"));

                for (Subject subject : Subject.values()) {
                    String value = student.getBoolean(subject.toString()) ? "" : "X";
                    Cell cell = row.createCell(Arrays.asList(columnNames).indexOf(subject.toString()));
                    cell.setCellValue(value);
                    cell.setCellStyle(subjectCellStyles.get(subject));
                }

                if (student.getString("name").length() > longestNameLength) {
                    longestNameLength = student.getString("name").length();
                }

                rowNum++;
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }
        }

        sheet.createFreezePane(0, 1, 0, 1);
        // sheet.autoSizeColumn((short) 0); Not supported by App Engine
        sheet.setColumnWidth((short) 0, (int) (256 * longestNameLength * 1.1));
    }

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("contestTabulation").build();

    File body = new File();
    body.setTitle(docName);
    body.setMimeType("application/vnd.google-apps.spreadsheet");

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    workbook.write(outStream);
    ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
    InputStreamContent content = new InputStreamContent(
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", inStream);

    drive.files().insert(body, content).execute();
    workbook.close();
}

From source file:de.fme.alfresco.repo.web.scripts.datalist.DataListDownloadWebScript.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//from w  w  w.j  a  va 2s  . c o m
protected void populateBody(Object resource, Workbook workbook, Sheet sheet, List<QName> properties)
        throws IOException {
    NodeRef list = (NodeRef) resource;
    List<NodeRef> items = getItems(list);

    // Our various formats
    DataFormat formatter = workbook.createDataFormat();
    CreationHelper createHelper = workbook.getCreationHelper();

    CellStyle styleInt = workbook.createCellStyle();
    styleInt.setDataFormat(formatter.getFormat("0"));
    CellStyle styleDate = workbook.createCellStyle();
    styleDate.setDataFormat(formatter.getFormat("yyyy-mm-dd"));
    CellStyle styleDouble = workbook.createCellStyle();
    styleDouble.setDataFormat(formatter.getFormat("General"));
    CellStyle styleNewLines = workbook.createCellStyle();
    styleNewLines.setWrapText(true);

    CellStyle hlink_style = workbook.createCellStyle();
    Font hlink_font = workbook.createFont();
    hlink_font.setUnderline(Font.U_SINGLE);
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hlink_style.setFont(hlink_font);

    // Export the items
    int rowNum = 1, colNum = 0;
    for (NodeRef item : items) {
        Row r = sheet.createRow(rowNum);

        colNum = 0;
        for (QName prop : properties) {
            Cell c = r.createCell(colNum);

            Serializable val = nodeService.getProperty(item, prop);
            if (val == null) {
                // Is it an association, or just missing?
                List<AssociationRef> assocs = nodeService.getTargetAssocs(item, prop);
                Set<QName> qnames = new HashSet<QName>(1, 1.0f);
                qnames.add(prop);
                List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(item, qnames);
                if (assocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    int lines = 1;

                    for (AssociationRef ref : assocs) {
                        NodeRef child = ref.getTargetRef();
                        QName type = nodeService.getType(child);
                        if (ContentModel.TYPE_PERSON.equals(type)) {
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_FIRSTNAME));
                            text.append(" ");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_LASTNAME));
                        } else if (ContentModel.TYPE_CONTENT.equals(type)) {
                            // TODO Link to the content
                            if (text.length() > 0) {
                                text.append('\n');
                                lines++;
                            }
                            text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                            text.append(" (");
                            text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                            text.append(") ");
                            /*MessageFormat.format(CONTENT_DOWNLOAD_PROP_URL, new Object[] {
                                    child.getStoreRef().getProtocol(),
                                    child.getStoreRef().getIdentifier(),
                                    child.getId(),
                                    URLEncoder.encode((String)nodeService.getProperty(child, ContentModel.PROP_TITLE)),
                                    URLEncoder.encode(ContentModel.PROP_CONTENT.toString()) });
                            */
                            /*currently only one link per cell possible
                             * Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);
                             *link.setAddress("http://poi.apache.org/");
                             *c.setHyperlink(link);
                             *c.setCellStyle(hlink_style);*/
                        } else if (ApplicationModel.TYPE_FILELINK.equals(type)) {
                            NodeRef linkRef = (NodeRef) nodeService.getProperty(child,
                                    ContentModel.PROP_LINK_DESTINATION);
                            if (linkRef != null) {
                                if (text.length() > 0) {
                                    text.append('\n');
                                    lines++;
                                }
                                text.append("link to: ");
                                try {
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(linkRef, ContentModel.PROP_TITLE));
                                    text.append(") ");
                                } catch (Exception e) {
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_NAME));
                                    text.append(" (");
                                    text.append(nodeService.getProperty(child, ContentModel.PROP_TITLE));
                                    text.append(") ");

                                }
                            }
                        } else {
                            System.err.println("TODO: handle " + type + " for " + child);
                        }
                    }

                    String v = text.toString();
                    c.setCellValue(v);
                    if (lines > 1) {
                        c.setCellStyle(styleNewLines);
                        r.setHeightInPoints(lines * sheet.getDefaultRowHeightInPoints());
                    }
                } else if (childAssocs.size() > 0) {
                    StringBuffer text = new StringBuffer();
                    for (ChildAssociationRef childAssociationRef : childAssocs) {
                        NodeRef child = childAssociationRef.getChildRef();
                        QName type = nodeService.getType(child);
                        if (type.equals(ForumModel.TYPE_FORUM)) {
                            List<ChildAssociationRef> topics = nodeService.getChildAssocs(child);
                            if (topics.size() > 0) {
                                ChildAssociationRef topicRef = topics.get(0);
                                List<ChildAssociationRef> comments = nodeService
                                        .getChildAssocs(topicRef.getChildRef());
                                for (ChildAssociationRef commentChildRef : comments) {
                                    NodeRef commentRef = commentChildRef.getChildRef();

                                    ContentData data = (ContentData) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CONTENT);
                                    TemplateContentData contentData = new TemplateContentData(data,
                                            ContentModel.PROP_CONTENT);

                                    String commentString = "";
                                    try {
                                        commentString = contentData.getContentAsText(commentRef, -1);
                                    } catch (Exception e) {
                                        logger.warn("failed to extract content for nodeRef " + commentRef, e);
                                    }

                                    String creator = (String) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATOR);
                                    NodeRef person = personService.getPerson(creator, false);
                                    if (person != null) {
                                        creator = nodeService.getProperty(person, ContentModel.PROP_FIRSTNAME)
                                                + " "
                                                + nodeService.getProperty(person, ContentModel.PROP_LASTNAME);
                                    }
                                    Date created = (Date) nodeService.getProperty(commentRef,
                                            ContentModel.PROP_CREATED);

                                    text.append(creator).append(" (")
                                            .append(DateFormatUtils.format(created, "yyyy-MM-dd"))
                                            .append("):\n ");
                                    text.append(commentString).append("\n");
                                }
                            }
                        }
                    }
                    String v = text.toString();
                    c.setCellValue(v);
                    c.setCellStyle(styleNewLines);

                } else {
                    // This property isn't set
                    c.setCellType(Cell.CELL_TYPE_BLANK);
                }
            } else {
                // Regular property, set
                if (val instanceof String) {
                    c.setCellValue((String) val);
                    c.setCellStyle(styleNewLines);
                } else if (val instanceof Date) {
                    c.setCellValue((Date) val);
                    c.setCellStyle(styleDate);
                } else if (val instanceof Integer || val instanceof Long) {
                    double v = 0.0;
                    if (val instanceof Long)
                        v = (double) (Long) val;
                    if (val instanceof Integer)
                        v = (double) (Integer) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleInt);
                } else if (val instanceof Float || val instanceof Double) {
                    double v = 0.0;
                    if (val instanceof Float)
                        v = (double) (Float) val;
                    if (val instanceof Double)
                        v = (double) (Double) val;
                    c.setCellValue(v);
                    c.setCellStyle(styleDouble);
                } else {
                    // TODO
                    System.err.println("TODO: handle " + val.getClass().getName() + " - " + val);
                }
            }

            colNum++;
        }

        rowNum++;
    }

    // Sensible column widths please!
    colNum = 0;
    for (QName prop : properties) {
        try {
            sheet.autoSizeColumn(colNum);
        } catch (IllegalArgumentException e) {
            sheet.setColumnWidth(colNum, 40 * 256);
        }

        colNum++;
    }
}

From source file:de.fme.alfresco.repo.web.scripts.DeclarativeSpreadsheetWebScript.java

License:Open Source License

/**
 * Generates the spreadsheet, based on the properties in the header
 *  and a callback for the body./*from   ww  w  . ja  v a 2s .  c o  m*/
 */
public void generateSpreadsheet(Object resource, String format, WebScriptRequest req, Status status,
        Map<String, Object> model) throws IOException {
    Pattern qnameMunger = Pattern.compile("([A-Z][a-z]+)([A-Z].*)");

    // Build up the details of the header
    List<Pair<QName, Boolean>> propertyDetails = buildPropertiesForHeader(resource, format, req);
    String[] headings = new String[propertyDetails.size()];
    String[] descriptions = new String[propertyDetails.size()];
    boolean[] required = new boolean[propertyDetails.size()];
    for (int i = 0; i < headings.length; i++) {
        Pair<QName, Boolean> property = propertyDetails.get(i);
        if (property == null || property.getFirst() == null) {
            headings[i] = "";
            required[i] = false;
        } else {
            QName column = property.getFirst();
            required[i] = property.getSecond();

            // Ask the dictionary service nicely for the details
            PropertyDefinition pd = dictionaryService.getProperty(column);
            if (pd != null && pd.getTitle() != null) {
                // Use the friendly titles, which may even be localised!
                headings[i] = pd.getTitle();
                descriptions[i] = pd.getDescription();
            } else {
                // Nothing friendly found, try to munge the raw qname into
                //  something we can show to a user...
                String raw = column.getLocalName();
                raw = raw.substring(0, 1).toUpperCase() + raw.substring(1);

                Matcher m = qnameMunger.matcher(raw);
                if (m.matches()) {
                    headings[i] = m.group(1) + " " + m.group(2);
                } else {
                    headings[i] = raw;
                }
            }
        }
    }

    // Build a list of just the properties
    List<QName> properties = new ArrayList<QName>(propertyDetails.size());
    for (Pair<QName, Boolean> p : propertyDetails) {
        QName qn = null;
        if (p != null) {
            qn = p.getFirst();
        }
        properties.add(qn);
    }

    // Output
    if ("csv".equals(format)) {
        StringWriter sw = new StringWriter();
        CSVPrinter csv = new CSVPrinter(sw, CSVStrategy.EXCEL_STRATEGY);
        csv.println(headings);

        populateBody(resource, csv, properties);

        model.put(MODEL_CSV, sw.toString());
    } else {
        Workbook wb;
        if ("xlsx".equals(format)) {
            wb = new XSSFWorkbook();
            // TODO Properties
        } else {
            wb = new HSSFWorkbook();
            // TODO Properties
        }

        // Add our header row
        Sheet sheet = wb.createSheet("Export");
        Row hr = sheet.createRow(0);
        try {
            sheet.createFreezePane(0, 1);
        } catch (IndexOutOfBoundsException e) {
            //https://issues.apache.org/bugzilla/show_bug.cgi?id=51431 & http://stackoverflow.com/questions/6469693/apache-poi-clearing-freeze-split-panes
        }
        Font fb = wb.createFont();
        fb.setBoldweight(Font.BOLDWEIGHT_BOLD);
        Font fi = wb.createFont();
        fi.setBoldweight(Font.BOLDWEIGHT_BOLD);
        fi.setItalic(true);

        CellStyle csReq = wb.createCellStyle();
        csReq.setFont(fb);
        CellStyle csOpt = wb.createCellStyle();
        csOpt.setFont(fi);

        // Populate the header
        Drawing draw = null;
        for (int i = 0; i < headings.length; i++) {
            Cell c = hr.createCell(i);
            c.setCellValue(headings[i]);

            if (required[i]) {
                c.setCellStyle(csReq);
            } else {
                c.setCellStyle(csOpt);
            }

            if (headings[i].length() == 0) {
                sheet.setColumnWidth(i, 3 * 250);
            } else {
                sheet.setColumnWidth(i, 18 * 250);
            }

            if (descriptions[i] != null && descriptions[i].length() > 0) {
                // Add a description for it too
                if (draw == null) {
                    draw = sheet.createDrawingPatriarch();
                }
                ClientAnchor ca = wb.getCreationHelper().createClientAnchor();
                ca.setCol1(c.getColumnIndex());
                ca.setCol2(c.getColumnIndex() + 1);
                ca.setRow1(hr.getRowNum());
                ca.setRow2(hr.getRowNum() + 2);

                Comment cmt = draw.createCellComment(ca);
                cmt.setAuthor("");
                cmt.setString(wb.getCreationHelper().createRichTextString(descriptions[i]));
                cmt.setVisible(false);
                c.setCellComment(cmt);
            }
        }

        // Have the contents populated
        populateBody(resource, wb, sheet, properties);

        // Save it for the template
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        model.put(MODEL_EXCEL, baos.toByteArray());
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.exporter.ExportWorkbook.java

License:Open Source License

/**
 * Adds headers stored in <code>headers</code> to the current sheet. If required, a special width
 * for the corresponding column can be set by providing a value in <code>headersWidth</code> using
 * header as key.<br/>/* w  ww . java2  s  .  c  o m*/
 * <b>IMPORTANT</b>: Headers are added in the order provided in <code>headers</code>.
 * 
 * @param headers
 *          headers to be added
 */
public void addHeaders(int sheetId, List<ExcelSheet.Header> headers) {
    Sheet sheet = getSheetById(sheetId);
    Drawing drawing = sheet.createDrawingPatriarch();
    CreationHelper factory = sheet.getWorkbook().getCreationHelper();
    Row row = sheet.createRow(this.getCurrentRowOfSheet(sheet, 3));
    int columnIndex = 0;
    for (ExcelSheet.Header header : headers) {
        int currColumnIndex = columnIndex;
        Cell cell = row.createCell(columnIndex);
        if (header.getDescription() != null) {
            ClientAnchor commentAnchor = factory.createClientAnchor();
            //Sizing the comment 1x3 cells
            commentAnchor.setCol1(cell.getColumnIndex());
            commentAnchor.setCol2(cell.getColumnIndex() + 1);
            commentAnchor.setRow1(row.getRowNum());
            commentAnchor.setRow2(row.getRowNum() + 3);

            Comment comment = drawing.createCellComment(commentAnchor);
            RichTextString str = factory.createRichTextString(header.getDescription());
            comment.setString(str);
            comment.setAuthor("");
            cell.setCellComment(comment);
        }

        setCellValue(cell, header.getLabel(), getHeaderTableStyle());
        Integer width = header.getWidth();
        if (width != null) {
            sheet.setColumnWidth(currColumnIndex, width.intValue());
        }
        columnIndex++;
    }

    LOGGER.debug("Added headers.");
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.nettoExport.NettoExcelTransformer.java

License:Open Source License

/**{@inheritDoc}**/
@Override/* w w w . ja v  a2 s. co m*/
public void transform(List<?> sourceList, OutputStream out, TypeOfBuildingBlock typeOfBuildingBlock) {

    ColumnStructure[] columns = tableStructure.getColumns();

    try {
        Workbook workbook = createWorkbook();

        Sheet sheet = workbook.createSheet();
        configSheetName(sheet, typeOfBuildingBlock);

        Map<IteraExcelStyle, CellStyle> createdStyles = ExcelStylesCreator.createStyles(workbook);
        CellStyle headerStyle = createdStyles.get(IteraExcelStyle.HEADER);
        CellStyle dataStyle = createdStyles.get(IteraExcelStyle.DATA);
        CellStyle dataDateStyle = createdStyles.get(IteraExcelStyle.DATA_DATE);

        // Create cell style for numbers
        CellStyle numCellStyle = workbook.createCellStyle();
        numCellStyle.cloneStyleFrom(dataStyle);
        short numFormatIndex = workbook.createDataFormat().getFormat("0.00");
        numCellStyle.setDataFormat(numFormatIndex);

        Row headerRow = sheet.createRow(0);

        int nextCol = 0;
        for (ColumnStructure columnStructure : columns) {
            Cell headerCell = headerRow.createCell(nextCol);
            headerCell.setCellValue(columnStructure.getColumnHeader());
            headerCell.setCellStyle(headerStyle);
            nextCol++;
        }

        int nextRow = 1;
        for (Object obj : sourceList) {
            if (obj instanceof BuildingBlock) {
                BuildingBlock bb = (BuildingBlock) obj;

                // skip virutal root element
                if (bb instanceof AbstractHierarchicalEntity<?>) {
                    AbstractHierarchicalEntity<?> hierarchicalEntity = (AbstractHierarchicalEntity<?>) bb;
                    if (hierarchicalEntity.isTopLevelElement()) {
                        continue;
                    }
                }

                Row row = sheet.createRow(nextRow);

                nextCol = 0;
                for (ColumnStructure columnStructure : columns) {
                    Cell cell = row.createCell(nextCol);

                    Object resolvedValue = columnStructure.resolveValue(bb);

                    if (resolvedValue instanceof Date) {
                        cell.setCellStyle(dataDateStyle);
                        cell.setCellValue((Date) resolvedValue);
                    } else if (resolvedValue instanceof Number) {
                        cell.setCellStyle(numCellStyle);
                        double doubleValue = ((Number) resolvedValue).doubleValue();
                        cell.setCellValue(doubleValue);
                    } else {
                        cell.setCellStyle(dataStyle);
                        cell.setCellValue(String.valueOf(resolvedValue));
                    }

                    ++nextCol;
                }

                ++nextRow;
            }
        }

        // auto format
        nextCol = 0;
        for (int col = 0; col < columns.length; col++) {
            sheet.autoSizeColumn(col);
            int columnCharWidth = sheet.getColumnWidth(col) / 256;
            if (columnCharWidth > MAX_COLUM_CHAR_WIDTH) {
                sheet.setColumnWidth(col, MAX_COLUM_CHAR_WIDTH * 256);
            }
        }

        workbook.write(out);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.exporter.TimeseriesExcelExportServiceImpl.java

License:Open Source License

private void adjustColumnWidths(Workbook workbook) {
    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
        Sheet sheet = workbook.getSheetAt(i);
        if (!AbstractIntroSheetGenerator.INTRO_SHEET_NAME.equals(sheet.getSheetName())) {
            sheet.autoSizeColumn(TimeseriesExcelImporter.BB_COL_NO, false);
            sheet.setColumnWidth(TimeseriesExcelImporter.DATE_COL_NO, DATE_COL_WIDTH);
            sheet.autoSizeColumn(TimeseriesExcelImporter.VALUE_COL_NO, false);
        }/* w  ww .j ava2  s. c  o m*/
    }
}

From source file:de.maklerpoint.office.Schnittstellen.Excel.ExportExcelXLSX.java

License:Open Source License

public void write() throws FileNotFoundException, IOException {
    FileOutputStream out = new FileOutputStream(new File(filename));
    Workbook wb;/*from w  ww . j  a  va 2  s  .  co  m*/

    wb = new XSSFWorkbook();

    Map<String, CellStyle> styles = createStyles(wb);
    Sheet sheet = wb.createSheet(sheetName);

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

    sheet.setAutobreaks(true);
    printSetup.setFitHeight((short) 1);
    printSetup.setFitWidth((short) 1);

    Row headerRow = sheet.createRow(0);
    headerRow.setHeightInPoints(12.75f);

    int[][] width = new int[titles.length][titles.length];

    for (int i = 0; i < titles.length; i++) {
        Cell cell = headerRow.createCell((short) i);
        cell.setCellValue(titles[i]);
        cell.setCellStyle(styles.get("header"));

        width[i][0] = titles[i].length();
    }

    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((short) j);
            if (data[i][j] == null)
                data[i][j] = "";

            cell.setCellValue(data[i][j].toString());

            if (data[i][j].toString().length() > width[j][0])
                width[j][0] = data[i][j].toString().length();
        }
    }

    for (short i = 0; i < titles.length; i++) {
        short widthShort = (short) (256 * (width[i][0] + 3));

        sheet.setColumnWidth(i, widthShort);
    }

    int position = (titles.length / 2) - 1;

    row = sheet.createRow(rownum + 3);
    cell = row.createCell((short) position);

    if (footName == null) {
        SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        cell.setCellValue("Export MaklerPoint vom " + df.format(new Date(System.currentTimeMillis()))
                + " - www.maklerpoint.de");
    } else {
        cell.setCellValue(footName);
    }

    sheet.setZoom(3, 4);

    wb.write(out);
    out.close();
}