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

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

Introduction

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

Prototype

Row createRow(int rownum);

Source Link

Document

Create a new row within the sheet and return the high level representation

Usage

From source file:com.github.camellabs.iot.cloudlet.geofencing.service.DefaultRouteService.java

License:Apache License

@Override
public byte[] exportRoutes(String client, String format) {
    try {/*from  w w  w .  jav  a2 s.  c o m*/
        List<List<String>> exportedRoutes = exportRoutes(client);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Routes report for " + client);

        for (int i = 0; i < exportedRoutes.size(); i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j < exportedRoutes.get(i).size(); j++) {
                row.createCell(j).setCellValue(exportedRoutes.get(i).get(j));
            }
        }

        ByteArrayOutputStream xlsBytes = new ByteArrayOutputStream();
        workbook.write(xlsBytes);
        xlsBytes.close();
        return xlsBytes.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.crab2died.ExcelUtils.java

License:Open Source License

private void generateSheet(Workbook workbook, List<?> data, Class clazz, boolean isWriteHeader,
        String sheetName) throws Excel4JException {

    Sheet sheet;
    if (null != sheetName && !"".equals(sheetName)) {
        sheet = workbook.createSheet(sheetName);
    } else {/*w ww. ja  v  a2  s. c o  m*/
        sheet = workbook.createSheet();
    }
    Row row = sheet.createRow(0);
    List<ExcelHeader> headers = Utils.getHeaderList(clazz);
    if (isWriteHeader) {
        // 
        for (int i = 0; i < headers.size(); i++) {
            row.createCell(i).setCellValue(headers.get(i).getTitle());
        }
    }
    // ?
    Object _data;
    for (int i = 0; i < data.size(); i++) {
        row = sheet.createRow(i + 1);
        _data = data.get(i);
        for (int j = 0; j < headers.size(); j++) {
            row.createCell(j).setCellValue(
                    Utils.getProperty(_data, headers.get(j).getFiled(), headers.get(j).getWriteConverter()));
        }
    }

}

From source file:com.github.crab2died.ExcelUtils.java

License:Open Source License

private void generateSheet(Workbook workbook, List<?> data, List<String> header, String sheetName) {

    Sheet sheet;
    if (null != sheetName && !"".equals(sheetName)) {
        sheet = workbook.createSheet(sheetName);
    } else {// w w w . j a  va  2 s  .co m
        sheet = workbook.createSheet();
    }

    int rowIndex = 0;
    if (null != header && header.size() > 0) {
        // 
        Row row = sheet.createRow(rowIndex++);
        for (int i = 0; i < header.size(); i++) {
            row.createCell(i, CellType.STRING).setCellValue(header.get(i));
        }
    }
    for (Object object : data) {
        Row row = sheet.createRow(rowIndex++);
        if (object.getClass().isArray()) {
            for (int j = 0; j < Array.getLength(object); j++) {
                row.createCell(j, CellType.STRING).setCellValue(Array.get(object, j).toString());
            }
        } else if (object instanceof Collection) {
            Collection<?> items = (Collection<?>) object;
            int j = 0;
            for (Object item : items) {
                row.createCell(j++, CellType.STRING).setCellValue(item.toString());
            }
        } else {
            row.createCell(0, CellType.STRING).setCellValue(object.toString());
        }
    }
}

From source file:com.github.igor_kudryashov.utils.excel.ExcelWriter.java

License:Apache License

/**
 * Creates new row in the worksheet/*from   www.  j  a  va2s . c om*/
 *
 * @param sheet
 *            Sheet
 * @param values
 *            the value of the new cell line
 * @param header
 *            <code>true</code> if this row is the header, otherwise
 *            <code>false</code>
 * @param withStyle
 *            <code>true</code> if in this row will be applied styles for
 *            the cells, otherwise <code>false</code>
 * @return created row
 */
public Row createRow(Sheet sheet, Object[] values, boolean header, boolean withStyle) {
    Row row;
    String sheetName = sheet.getSheetName();
    int rownum = 0;
    if (rows.containsKey(sheetName)) {
        rownum = rows.get(sheetName);
    }
    // create new row
    row = sheet.createRow(rownum);
    // create a cells of row
    for (int x = 0; x < values.length; x++) {
        Object o = values[x];
        Cell cell = row.createCell(x);
        if (o != null) {
            if (o.getClass().getName().contains("String")) {
                String value = (String) values[x];
                cell.setCellValue(value);
            } else if (o.getClass().getName().contains("Double")) {
                cell.setCellValue((Double) values[x]);
            } else if (o.getClass().getName().contains("Integer")) {
                cell.setCellValue((Integer) values[x]);
            } else if (o.getClass().getName().contains("Date")) {
                cell.setCellValue((Date) values[x]);
            }
            if (withStyle) {
                cell.setCellStyle(getCellStyle(rownum, values[x], header));
            }
        }
        // save max column width
        if (!header) {
            saveColumnWidth(sheet, x, o);
        }
    }
    // save the last number of row for this worksheet
    rows.put(sheetName, ++rownum);
    return row;
}

From source file:com.github.jaydsolanki.excelio.ExcelIO.java

private boolean insertCell(Object obj, Sheet sheet, int rowNo, int cellNo) {

    if (sheet == null) {
        return false;
    }//from  w w  w  .ja  v  a 2s  .c  o m

    Row row = sheet.getRow(rowNo);
    if (row == null) {
        row = sheet.createRow(rowNo);
    }
    Cell cell = row.getCell(cellNo);
    if (cell == null) {
        cell = row.createCell(cellNo);
    }
    cell.setCellValue(obj.toString());
    return true;
}

From source file:com.github.lucapino.sheetmaker.parsers.mediainfo.MediaInfoExtractor.java

private void print(String rootPath) throws Exception {
    FileFilter filter = new FileFilter() {

        @Override//  ww  w. jav  a2 s.c o m
        public boolean accept(File pathname) {
            String lowerCaseName = pathname.getName().toLowerCase();
            return (lowerCaseName.endsWith("ifo") && lowerCaseName.startsWith("vts"))
                    || lowerCaseName.endsWith("mkv") || lowerCaseName.endsWith("iso")
                    || lowerCaseName.endsWith("avi");
        }
    };
    // parse all the tree under rootPath
    File rootFolder = new File(rootPath);
    File[] files = rootFolder.listFiles();
    Arrays.sort(files);
    Map<File, List<File>> mediaMap = new TreeMap<>();
    for (File file : files) {
        System.out.println(file.getName());
        // name of the folder -> name of media
        List<File> fileList;
        if (file.isDirectory()) {
            fileList = recurseSubFolder(filter, file);
            if (!fileList.isEmpty()) {
                System.out.println("adding " + fileList);
                mediaMap.put(file, fileList);
            }
        } else {
            if (filter.accept(file)) {
                fileList = new ArrayList<>();
                fileList.add(file);
                System.out.println("adding " + fileList);
                mediaMap.put(file, fileList);
            }
        }
    }
    Set<File> fileNamesSet = mediaMap.keySet();
    File outputFile = new File("/home/tagliani/tmp/HD-report.xls");
    Workbook wb = new HSSFWorkbook(new FileInputStream(outputFile));
    Sheet sheet = wb.createSheet("Toshiba");

    MediaInfo MI = new MediaInfo();
    int j = 0;
    for (File mediaFile : fileNamesSet) {
        List<File> filesList = mediaMap.get(mediaFile);
        for (File fileInList : filesList) {
            List<String> audioTracks = new ArrayList<>();
            List<String> videoTracks = new ArrayList<>();
            List<String> subtitlesTracks = new ArrayList<>();
            MI.Open(fileInList.getAbsolutePath());

            String durationInt = MI.Get(MediaInfo.StreamKind.General, 0, "Duration", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);
            System.out.println(fileInList.getName() + " -> " + durationInt);
            if (StringUtils.isNotEmpty(durationInt) && Integer.valueOf(durationInt) >= 60 * 60 * 1000) {

                Row row = sheet.createRow(j);
                String duration = MI.Get(MediaInfo.StreamKind.General, 0, "Duration/String",
                        MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                // Create a cell and put a value in it.
                row.createCell(0).setCellValue(WordUtils.capitalizeFully(mediaFile.getName()));
                if (fileInList.getName().toLowerCase().endsWith("iso")
                        || fileInList.getName().toLowerCase().endsWith("ifo")) {
                    row.createCell(1).setCellValue("DVD");
                } else {
                    row.createCell(1)
                            .setCellValue(FilenameUtils.getExtension(fileInList.getName()).toUpperCase());
                }
                row.createCell(2).setCellValue(FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(mediaFile)));
                // row.createCell(3).setCellValue(fileInList.getAbsolutePath());
                row.createCell(3).setCellValue(duration);
                // MPEG-2 720x576 @ 25fps 16:9
                String format = MI.Get(MediaInfo.StreamKind.Video, 0, "Format", MediaInfo.InfoKind.Text,
                        MediaInfo.InfoKind.Name);
                row.createCell(4).setCellValue(format);
                String width = MI.Get(MediaInfo.StreamKind.Video, 0, "Width", MediaInfo.InfoKind.Text,
                        MediaInfo.InfoKind.Name);
                String height = MI.Get(MediaInfo.StreamKind.Video, 0, "Height", MediaInfo.InfoKind.Text,
                        MediaInfo.InfoKind.Name);
                row.createCell(5).setCellValue(width + "x" + height);
                String fps = MI.Get(MediaInfo.StreamKind.Video, 0, "FrameRate", MediaInfo.InfoKind.Text,
                        MediaInfo.InfoKind.Name);
                row.createCell(6).setCellValue(fps);
                String aspectRatio = MI.Get(MediaInfo.StreamKind.Video, 0, "DisplayAspectRatio/String",
                        MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                row.createCell(7).setCellValue(aspectRatio);

                int audioStreamNumber = MI.Count_Get(MediaInfo.StreamKind.Audio);
                for (int i = 0; i < audioStreamNumber; i++) {
                    String audioTitle = MI.Get(MediaInfo.StreamKind.Audio, i, "Title", MediaInfo.InfoKind.Text,
                            MediaInfo.InfoKind.Name);
                    String language = MI.Get(MediaInfo.StreamKind.Audio, i, "Language/String3",
                            MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                    String codec = MI.Get(MediaInfo.StreamKind.Audio, i, "Codec", MediaInfo.InfoKind.Text,
                            MediaInfo.InfoKind.Name);
                    String channels = MI.Get(MediaInfo.StreamKind.Audio, i, "Channel(s)",
                            MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                    String sampleRate = MI.Get(MediaInfo.StreamKind.Audio, i, "SamplingRate/String",
                            MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                    // AC3 ITA 5.1 48.0KHz
                    StringBuilder sb = new StringBuilder();
                    if (StringUtils.isEmpty(audioTitle)) {
                        sb.append(codec).append(" ").append(language.toUpperCase()).append(" ")
                                .append(channels);
                    } else {
                        sb.append(audioTitle);
                    }
                    sb.append(" ").append(sampleRate);
                    audioTracks.add(sb.toString());
                }

                int textStreamNumber = MI.Count_Get(MediaInfo.StreamKind.Text);
                for (int i = 0; i < textStreamNumber; i++) {
                    String textLanguage = MI.Get(MediaInfo.StreamKind.Text, i, "Language/String",
                            MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
                    subtitlesTracks.add(textLanguage);
                }
                MI.Close();
                row.createCell(8).setCellValue(audioTracks.toString());
                row.createCell(9).setCellValue(subtitlesTracks.toString());
                j++;
            }

        }

        //            System.out.println(mediaName);
    }
    try (FileOutputStream fileOut = new FileOutputStream(outputFile)) {
        wb.write(fileOut);
    }

}

From source file:com.github.luischavez.lat.excel.Excel.java

License:Open Source License

protected void setContent(Workbook workbook, Sheet sheet, String groupName) {
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setColor(HSSFColor.WHITE.index);
    style.setFont(font);//from w ww .ja  v  a2  s.  c  o  m
    style.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);

    Row row = sheet.createRow(0);
    this.createCell(0, row, style, "#");
    this.createCell(1, row, style, "Matricula");
    this.createCell(2, row, style, "Nombres");
    this.createCell(3, row, style, "Apellidos");
    for (int i = 0; i < 6; i++) {
        this.createCell(4 + i, row, style, "Practica #" + (i + 1));
    }
    this.createCell(10, row, style, "Promedio");

    int current = 1;
    RowList students = this.studentController.getByGroup(groupName);
    long groupId = this.groupController.getGroupId(groupName);
    for (com.github.luischavez.database.link.Row student : students) {
        long studentId = student.value("student_id", Long.class);
        String credential = student.value("credential", String.class);
        String firstName = student.value("first_name", String.class);
        String lastName = student.value("last_name", String.class);
        row = sheet.createRow(current);
        this.createNumber(0, row, null, current++);
        this.createCell(1, row, null, credential);
        this.createCell(2, row, null, firstName);
        this.createCell(3, row, null, lastName);
        for (int i = 0; i < 6; i++) {
            double qualification = this.qualificationController.get(groupId, studentId, i + 1);
            if (0 > qualification) {
                qualification = 0;
            }
            this.createNumber(4 + i, row, null, qualification);
        }
        this.createFormula(10, row, style, String.format("AVERAGE(E%d:J%d)", current, current));
    }
    row = sheet.createRow(current);
    this.createFormula(10, row, style, String.format("AVERAGE(K%d:K%d)", 2, current));
}

From source file:com.github.mutationmapper.MutationMapperResultViewController.java

License:Open Source License

private void writeResultsToExcel(final File f) throws IOException {
    final Service<Void> service = new Service<Void>() {
        @Override//  ww w  .j ava 2s.  c  o  m
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws IOException {
                    BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f));
                    Workbook wb = new XSSFWorkbook();
                    //CellStyle hlink_style = wb.createCellStyle();
                    //Font hlink_font = wb.createFont();
                    //hlink_font.setUnderline(Font.U_SINGLE);
                    //hlink_font.setColor(IndexedColors.BLUE.getIndex());
                    //hlink_style.setFont(hlink_font);
                    //CreationHelper createHelper = wb.getCreationHelper();
                    Sheet sheet = wb.createSheet();
                    Row row = null;
                    int rowNo = 0;
                    row = sheet.createRow(rowNo++);
                    String header[] = { "#", "Symbol", "Gene", "Transcript", "Genomic Coordinate", "Ref", "Var",
                            "CDS", "Consequence", "CDS Consequence", "Protein Consequence", "Exon/Intron",
                            "Colocated Variants", "Polyphen", "Sift", "Seq Input" };
                    for (int col = 0; col < header.length; col++) {
                        Cell cell = row.createCell(col);
                        cell.setCellValue(header[col]);
                    }

                    updateMessage("Writing results . . .");
                    updateProgress(0, displayData.size());
                    int n = 0;
                    for (MutationMapperResult r : displayData) {
                        n++;
                        updateMessage("Writing result " + n + " . . .");
                        row = sheet.createRow(rowNo++);
                        int col = 0;
                        ArrayList<String> resultsToWrite = getResultArray(r);
                        for (String s : resultsToWrite) {
                            Cell cell = row.createCell(col++);
                            cell.setCellValue(s);
                        }
                        updateProgress(n, displayData.size());
                    }

                    updateMessage("Wrote " + displayData.size() + " results to file.");
                    wb.write(bo);
                    bo.close();
                    return null;
                }
            };
        }

    };

    service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("File Saved");
            alert.setHeaderText("Displayed results saved to " + f.getName());
            alert.setContentText("Open this file now?");
            ButtonType yesButton = ButtonType.YES;
            ButtonType noButton = ButtonType.NO;
            alert.getButtonTypes().setAll(yesButton, noButton);
            Optional<ButtonType> response = alert.showAndWait();
            if (response.get() == yesButton) {
                try {
                    openFile(f);
                } catch (Exception ex) {
                    Alert openError = getExceptionDialog(ex);
                    openError.setTitle("Open Failed");
                    openError.setHeaderText("Could not open ouput file.");
                    openError.setContentText(
                            "Exception encountered when attempting to open " + "the saved file. See below:");
                    openError.showAndWait();
                }
            }
        }
    });
    service.setOnCancelled(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            Alert writeCancelled = new Alert(AlertType.INFORMATION);
            writeCancelled.setTitle("Cancelled writing to file");
            writeCancelled.setHeaderText("User cancelled writing primers to file.");
            writeCancelled.showAndWait();
        }
    });
    service.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent e) {
            Alert writeFailed = getExceptionDialog(e.getSource().getException());
            writeFailed.setTitle("Write Failed");
            writeFailed.setHeaderText("Could not write ouput file.");
            writeFailed.setContentText(
                    "Exception encountered when attempting to write " + "results to file. See below:");
            writeFailed.showAndWait();

        }
    });
    service.start();
}

From source file:com.github.pascalgn.jiracli.testutil.ExcelUtils.java

License:Apache License

/**
 * @param row 0-based index//from   ww w  .ja  va  2  s  .c  om
 * @param column 0-based index
 */
public static void writeCell(Sheet sheet, int row, int column, String value) {
    Row r = sheet.getRow(row);
    if (r == null) {
        r = sheet.createRow(row);
    }
    Cell cell = r.getCell(column);
    if (cell == null) {
        cell = r.createCell(column, Cell.CELL_TYPE_STRING);
    }
    cell.setCellValue(value);
}

From source file:com.globalsight.everest.qachecks.DITAQAChecker.java

License:Apache License

private Row getRow(Sheet p_sheet, int p_col) {
    Row row = p_sheet.getRow(p_col);//from w ww .  j  a va2s  .  c o  m
    if (row == null)
        row = p_sheet.createRow(p_col);
    return row;
}