Example usage for org.apache.poi.hssf.usermodel HSSFRow getCell

List of usage examples for org.apache.poi.hssf.usermodel HSSFRow getCell

Introduction

In this page you can find the example usage for org.apache.poi.hssf.usermodel HSSFRow getCell.

Prototype

@Override
public HSSFCell getCell(int cellnum) 

Source Link

Document

Get the hssfcell representing a given column (logical cell) 0-based.

Usage

From source file:gda.hrpd.data.ExcelWorkbook.java

License:Open Source License

/**
 * modify if exist, or create if not exist, a cell in the specified row at specified position with the specified
 * value.//from   ww w .j a  va  2  s .c  o m
 * 
 * @param row
 * @param column
 * @param value
 * @throws IOException
 */
public void setCellValue(HSSFRow row, int column, String value) throws IOException {
    HSSFCell cell = row.getCell(column);
    if (cell == null)
        // add more cell to the row
        if (!writeable) {
            logger.error("Cannot create a new cell in file {}.", this.filename);
            throw new IOException("Cannot write to file {}." + this.filename);
        }

    cell = row.createCell((short) column);
    cell.setCellValue(new HSSFRichTextString(value));
}

From source file:gda.hrpd.data.ExcelWorkbook.java

License:Open Source License

/**
 * modify if exist, or create if not exist, a cell in the specified row at specified position with the specified
 * value./*from   ww  w.ja va2s .c  o  m*/
 * 
 * @param row
 * @param column
 * @param value
 * @throws IOException 
 */
public void setCellValue(HSSFRow row, int column, double value) throws IOException {
    HSSFCell cell = row.getCell(column);
    if (cell == null)
        if (!writeable) {
            logger.error("Cannot create a new sheet in file {}.", this.filename);
            throw new IOException("Cannot write to file {}." + this.filename);
        }

    // add more cell to the row
    cell = row.createCell((short) column);
    cell.setCellValue(value);
}

From source file:gda.hrpd.data.ExcelWorkbook.java

License:Open Source License

/**
 * modify if exist, or create if not exist, a cell in the specified row at specified position with the specified
 * value./*from   w  w w . j a  va  2  s.  c o  m*/
 * 
 * @param row
 * @param column
 * @param value
 * @throws IOException
 */
public void setCellValue(HSSFRow row, int column, boolean value) throws IOException {
    HSSFCell cell = row.getCell(column);
    if (cell == null)
        if (!writeable) {
            logger.error("Cannot create a new sheet in file {}.", this.filename);
            throw new IOException("Cannot write to file {}." + this.filename);
        }

    // add more cell to the row
    cell = row.createCell((short) column);
    cell.setCellValue(value);
}

From source file:gda.hrpd.data.ExcelWorkbook.java

License:Open Source License

/**
 * modify if exist, or create if not exist, a cell in the specified row at specified position with the specified
 * value.//  w  w w  . j  a  va 2  s  .  com
 * 
 * @param row
 * @param column
 * @param date
 * @throws IOException
 */
public void setCellValue(HSSFRow row, int column, Date date) throws IOException {
    HSSFCell cell = row.getCell(column);
    if (cell == null) {
        if (!writeable) {
            logger.error("Cannot create a new sheet in file {}.", this.filename);
            throw new IOException("Cannot write to file {}." + this.filename);
        }

        // we style the cell as a date (and time). It is important to
        // create a new cell style from the workbook otherwise you can end
        // up modifying the built in style and effecting not only this cell
        // but other cells.
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
        cell = row.createCell((short) column);
        cell.setCellValue(date);
        cell.setCellStyle(cellStyle);
    } else {
        cell.setCellValue(date);
    }
}

From source file:gda.hrpd.data.HSSF.java

License:Apache License

/**
 * Method main Given 1 argument takes that as the filename, inputs it and dumps the cell values/types out to sys.out
 * given 2 arguments where the second argument is the word "write" and the first is the filename - writes out a
 * sample (test) spreadsheet (see public HSSF(String filename, boolean write)). given 2 arguments where the first is
 * an input filename and the second an output filename (not write), attempts to fully read in the spreadsheet and
 * fully write it out. given 3 arguments where the first is an input filename and the second an output filename (not
 * write) and the third is "modify1", attempts to read in the spreadsheet, deletes rows 0-24, 74-99. Changes cell at
 * row 39, col 3 to "MODIFIED CELL" then writes it out. Hence this is "modify test 1". If you take the output from
 * the write test, you'll have a valid scenario.
 *
 * @param args//from   w  w w  .j a va  2s.  c  o m
 */

public static void main(String[] args) {
    if (args.length < 2) {

        /*
         * try { HSSF hssf = new HSSF(args[ 0 ]); System.out.println("Data dump:\n"); HSSFWorkbook wb =
         * hssf.hssfworkbook; for (int k = 0; k < wb.getNumberOfSheets(); k++) { System.out.println("Sheet " + k);
         * HSSFSheet sheet = wb.getSheetAt(k); int rows = sheet.getPhysicalNumberOfRows(); for (int r = 0; r < rows;
         * r++) { HSSFRow row = sheet.getPhysicalRowAt(r); int cells = row.getPhysicalNumberOfCells();
         * System.out.println("ROW " + row.getRowNum()); for (int c = 0; c < cells; c++) { HSSFCell cell =
         * row.getPhysicalCellAt(c); String value = null; switch (cell.getCellType()) { case
         * HSSFCell.CELL_TYPE_FORMULA : value = "FORMULA "; break; case HSSFCell.CELL_TYPE_NUMERIC : value =
         * "NUMERIC value=" + cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING : value = "STRING
         * value=" + cell.getStringCellValue(); break; default : } System.out.println("CELL col=" +
         * cell.getCellNum() + " VALUE=" + value); } } } } catch (Exception e) { e.printStackTrace(); }
         */
    } else if (args.length == 2) {
        if (args[1].toLowerCase().equals("write")) {
            System.out.println("Write mode");
            try {
                long time = System.currentTimeMillis();
                // HSSF hssf = new HSSF(args[ 0 ], true);

                System.out.println("" + (System.currentTimeMillis() - time) + " ms generation time");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("readwrite test");
            try {
                HSSF hssf = new HSSF(args[0]);

                // HSSFStream hssfstream = hssf.hssfstream;
                HSSFWorkbook wb = hssf.hssfworkbook;
                FileOutputStream stream = new FileOutputStream(args[1]);

                // HSSFCell cell = new HSSFCell();
                // cell.setCellNum((short)3);
                // cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                // cell.setCellValue(-8009.999);
                // hssfstream.modifyCell(cell,0,(short)6);
                wb.write(stream);
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if ((args.length == 3) && args[2].toLowerCase().equals("modify1")) {
        try // delete row 0-24, row 74 - 99 && change cell 3 on row 39 to string "MODIFIED CELL!!"
        {
            HSSF hssf = new HSSF(args[0]);

            // HSSFStream hssfstream = hssf.hssfstream;
            HSSFWorkbook wb = hssf.hssfworkbook;
            FileOutputStream stream = new FileOutputStream(args[1]);
            HSSFSheet sheet = wb.getSheetAt(0);

            for (int k = 0; k < 25; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            for (int k = 74; k < 100; k++) {
                HSSFRow row = sheet.getRow(k);

                sheet.removeRow(row);
            }
            HSSFRow row = sheet.getRow(39);
            HSSFCell cell = row.getCell((short) 3);

            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
            cell.setCellValue(new HSSFRichTextString("MODIFIED CELL!!!!!"));

            // HSSFCell cell = new HSSFCell();
            // cell.setCellNum((short)3);
            // cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
            // cell.setCellValue(-8009.999);
            // hssfstream.modifyCell(cell,0,(short)6);
            wb.write(stream);
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:gda.hrpd.data.SampleExperimentSummary.java

License:Open Source License

/**
 * gets sample information for specified sample from spreadsheet 0
 * /*ww w .ja v a 2 s .  c  o m*/
 * @param sampleNo
 */
public void loadExperimentInfo(int sampleNo) {

    HSSFRow row = sheet.getRow(sampleNo + rowOffset);
    carouselNo = row.getCell(0).getRichStringCellValue().getString();
    runNumber = row.getCell(1).getRichStringCellValue().getString();
    date = row.getCell(2).getRichStringCellValue().getString();
    time = row.getCell(3).getRichStringCellValue().getString();
    beamline = row.getCell(4).getRichStringCellValue().getString();
    project = row.getCell(5).getRichStringCellValue().getString();
    experiment = row.getCell(6).getRichStringCellValue().getString();
    accumulationTime = row.getCell(7).getRichStringCellValue().getString();
}

From source file:gda.hrpd.data.SampleExperimentSummary.java

License:Open Source License

/**
 * @param sampleNo/*from  w w  w . ja  va  2 s. c  om*/
 */
public void saveExperimentInfo(int sampleNo) {
    HSSFRow row = sheet.getRow(sampleNo + rowOffset);
    HSSFCell cell = row.getCell((short) 1);
    if (cell == null)
        cell = row.createCell((short) 1);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(runNumber));
    cell = row.getCell((short) 2);
    if (cell == null)
        cell = row.createCell((short) 2);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(date));
    cell = row.getCell((short) 3);
    if (cell == null)
        cell = row.createCell((short) 3);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(time));
    cell = row.getCell((short) 4);
    if (cell == null)
        cell = row.createCell((short) 4);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(beamline));
    cell = row.getCell((short) 5);
    if (cell == null)
        cell = row.createCell((short) 5);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(project));
    cell = row.getCell((short) 6);
    if (cell == null)
        cell = row.createCell((short) 6);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(experiment));
    cell = row.getCell((short) 7);
    if (cell == null)
        cell = row.createCell((short) 7);
    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(new HSSFRichTextString(accumulationTime));
}

From source file:gda.hrpd.sample.Sample.java

License:Open Source License

/**
 * read existing data only {@inheritDoc}
 *
 * @see gda.hrpd.SampleInfo#loadSampleInfo(int)
 *//*from   ww w.  ja va  2  s  . c  o  m*/
@Override
public void loadSampleInfo(int sampleNo) {
    if (!opened) {
        logger.error("Sample Information File is not opened yet.");
        throw new IllegalStateException("Sample Information file " + this.filename + " must be opened first.");
    }
    logger.info("Load sample information from {} for sample number {}", getSampleInfoFile(), sampleNo);
    HSSFRow row = sampleInfo.getRow(sampleNo + rowOffset);
    if (row == null) {
        logger.error("specified sample Number {} does not exist.", sampleNo);
        JythonServerFacade.getInstance()
                .print("No sample information is provided for sample number " + sampleNo);
    } else {
        carouselNo = excel.getCellValue(row.getCell(0));
        sampleID = excel.getCellValue(row.getCell(1));
        sampleName = excel.getCellValue(row.getCell(2));
        description = excel.getCellValue(row.getCell(3));
        title = excel.getCellValue(row.getCell(4));
        comment = excel.getCellValue(row.getCell(5));
        logger.info("Sample information for sample number {} is loaded.", sampleNo);
    }
}

From source file:gda.hrpd.sample.SpreadsheetTest.java

License:Open Source License

/**
 * @param sampleNo//from  w w  w  . ja v a2s.  co m
 */
public void loadSampleInfo(int sampleNo) {
    if (!opened) {
        logger.error("Sample Information File is not opened yet.");
        throw new IllegalStateException("Sample Information file " + this.filename + " must be opened first.");
    }
    logger.info("Load sample information from {} for sample number {}", getSampleInfoFile(), sampleNo);
    HSSFRow row = sampleInfo.getRow(sampleNo + rowOffset);
    if (row == null) {
        logger.error("specified sample Number {} does not exist.", sampleNo);
        JythonServerFacade.getInstance()
                .print("No sample information is provided for sample number " + sampleNo);
    } else {
        String carouselNo = excel.getCellValue(row.getCell(0));
        String sampleID = excel.getCellValue(row.getCell(1));
        String sampleName = excel.getCellValue(row.getCell(2));
        String description = excel.getCellValue(row.getCell(3));
        String title = excel.getCellValue(row.getCell(4));
        String comment = excel.getCellValue(row.getCell(5));
        logger.info("Sample information for sample number {} is loaded.", sampleNo);
        System.out.println(carouselNo + "\t" + sampleID + "\t" + sampleName + "\t" + description + "\t" + title
                + "\t" + comment);
    }
}

From source file:gov.nih.nci.cabig.caaers.dataimport.AgentSpecificTermsImporter.java

License:BSD License

public Map<String, Object> importFile() throws Exception {

    POIFSFileSystem poifs;/*from   w  w  w .ja va 2 s.c o m*/
    HSSFWorkbook wb;
    HSSFSheet sh = null;

    boolean isExcel = file.getName().endsWith(".xls");
    boolean isCSV = file.getName().endsWith(".csv");

    Map<String, Object> results = new HashMap<String, Object>();
    int rowCount = 0;
    int columnsCount = 0;
    Map<String, Agent> agents = new HashMap<String, Agent>();
    Map<String, Agent> missingAgents = new HashMap<String, Agent>();
    Set<String> missingTerms = new HashSet<String>();
    Map<String, String> asaelCache = new HashMap<String, String>();
    int asael;

    // wipe out the table
    agentSpecificTermDao.deleteAll();
    studyDao.deleteAllExpectedTerms();
    // if (true) return null;

    // get needed headers
    if (isExcel) {
        poifs = new POIFSFileSystem(new FileInputStream(file));
        wb = new HSSFWorkbook(poifs);
        sh = wb.getSheetAt(0);
        rowCount = sh.getLastRowNum();
        columnsCount = sh.getRow(0).getLastCellNum();

        for (byte i = 0; i < columnsCount; i++) {
            HSSFCell cell = sh.getRow(0).getCell(i);
            if (headers.containsKey(cell.getStringCellValue())) {
                headers.remove(cell.getStringCellValue());
                headers.put(cell.getStringCellValue(), Short.valueOf(i));
            }
        }
    }

    InputStream ir = null;
    Reader r = null;
    BufferedReader br = null;

    if (isCSV) {
        // readLines
        rowCount = 0;
        ir = new FileInputStream(file);
        r = new InputStreamReader(ir);
        br = new BufferedReader(r);
        String s = br.readLine();
        while (s != null) {
            if (rowCount == 0) {
                String[] _s = s.split("[\\|]{1}");
                for (byte j = 0; j < _s.length; j++) {
                    // System.out.println(_s[j]);
                    if (headers.containsKey(_s[j])) {
                        headers.remove(_s[j]);
                        headers.put(_s[j], Short.valueOf(j));
                    }
                }
            }
            rowCount++;
            s = br.readLine();
        }
        br.close();
        r.close();
        ir.close();

        ir = new FileInputStream(file);
        r = new InputStreamReader(ir);
        br = new BufferedReader(r);
    }

    /*
            System.out.println(rowCount);
            for (Map.Entry e : headers.entrySet()) {
    System.out.println(e.getKey() + "=>" + e.getValue());
            }
    */

    agents.clear();
    missingTerms.clear();
    missingAgents.clear();
    asael = 0;
    int duplicateAgentTerms = 0;

    //
    String nsc = "";
    String ctcae_category = "";
    String ctcae_version = "0.0";
    String ae_term = "";
    String other_toxicity = "";

    // Loading ASAE list
    // if (true) {  return null; }

    int i = 1;
    while (i <= rowCount) {

        nsc = "";

        if (isExcel) {
            HSSFRow row = sh.getRow(i);
            if (row != null) {
                nsc = getCellData("", i, row.getCell((short) headers.get("NSC")));
                ctcae_category = getCellData("", i, row.getCell((short) headers.get("CTCAE_CATEGORY")));
                ctcae_version = getCellData("", i, row.getCell((short) headers.get("CTCAE_VERSION")));
                ae_term = getCellData("", i, row.getCell((short) headers.get("AE_TERM")));
                other_toxicity = getCellData("", i, row.getCell((short) headers.get("OTHER_TOXICITY")));
            }
        } else {
            String s;
            s = br.readLine();
            if (s != null) {
                String[] _s = s.split("[\\|]{1}");
                if (i > 1 && _s.length > 1) {
                    nsc = _s[headers.get("NSC")];
                    ctcae_category = _s[headers.get("CTCAE_CATEGORY")];
                    try {
                        ctcae_version = _s[headers.get("CTCAE_VERSION")].trim();
                    } catch (NumberFormatException e) {
                        //                                System.out.println(s);
                        return null;
                    }
                    ae_term = _s[headers.get("AE_TERM")];
                    if (_s.length - 1 >= headers.get("OTHER_TOXICITY"))
                        other_toxicity = _s[headers.get("OTHER_TOXICITY")];
                    else
                        other_toxicity = "";
                }
            }
        }

        if (nsc.trim().equals("")) {
            i++;
            continue;
        } else {
            // System.out.println(String.format("%s). NSC:%s,   V:%s,   C:%s,   T:%s", i, nsc, ctcae_version, ctcae_category, ae_term));
        }

        Agent a = agents.get(nsc);
        if (a == null) {
            a = agentDao.getByNscNumber(nsc);
            // System.out.println(asael + ". OK. Found agent [" + a.getName() + "] for NSC: [" + nsc + "]");
            agents.put(nsc, a);
        }

        if (a != null) {
            AgentSpecificCtcTerm t = new AgentSpecificCtcTerm();
            t.setAgent(a);
            t.setOtherToxicity(other_toxicity);

            List<CtcTerm> list = terminologyRepository.getCtcTerm(ctcae_category, ctcae_version, ae_term);
            if (list.size() == 0) {
                // System.out.println("<ERROR>: Term not found: " + ae_term + ", Category: " + ctcae_category + ", CTCAE Version: " + ctcae_version);
                missingTerms.add("Term not found: " + ae_term + ", Category: " + ctcae_category
                        + ", CTCAE Version: " + ctcae_version);
            } else {
                t.setCtcTerm(list.get(0));
                if (persistASAE(t))
                    asael++;
                else
                    duplicateAgentTerms++;
            }

            agentSpecificTermDao.evict(t);

        } else {
            if (!missingAgents.containsKey(nsc)) {
                // System.out.println("<ERROR>: The agent was not found by its NSC: " + nsc);
                missingAgents.put(nsc, null);
            }
        }

        i++;
    }

    if (isCSV) {
        br.close();
        r.close();
        ir.close();
    }

    results.put(KEY_MISSING_TERMS, missingTerms);
    results.put(KEY_PROCESSED_AGENTS, agents.size() - missingAgents.size());
    results.put(KEY_PROCESSED_AGENTTERMS, asael);
    results.put(KEY_MISSING_AGENTS, missingAgents);
    results.put(KEY_DUPLICATE_AGENT_TERMS, duplicateAgentTerms);

    return results;
}