List of usage examples for org.apache.poi.hssf.usermodel HSSFSheet getRow
@Override public HSSFRow getRow(int rowIndex)
From source file:FormatConvert.exceloperation.Excel2csv.java
public static void copySheets2CSV(HSSFSheet sheet, String csvfile) { int maxColumnNum = 0; try {// ww w. j ava 2 s. c o m FileWriter fw = new FileWriter(csvfile); String str = ""; for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { HSSFRow srcRow = sheet.getRow(i); if (srcRow != null) { for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) { if (j != srcRow.getLastCellNum()) { str = str + srcRow.getCell(j).getStringCellValue() + ","; } else { str = str + srcRow.getCell(j).getStringCellValue() + "\r\n"; } } fw.append(str); } str = ""; } fw.flush(); fw.close(); } catch (IOException ex) { } //Util.copyPictures(newSheet,sheet) ; }
From source file:fr.amapj.view.views.importdonnees.tools.AbstractImporter.java
License:Open Source License
private void processFile() throws IOException { // Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(new ByteArrayInputStream(baos.toByteArray())); DataFormatter df = new DataFormatter(Locale.FRANCE); // Get first sheet from the workbook HSSFSheet sheet = workbook.getSheetAt(0); int numCol = getNumCol(); List<T> existing = getAllDataInDatabase(); List<T> utilisateurs = new ArrayList<>(); int lastRowNum = sheet.getLastRowNum(); for (int numLigne = 2; numLigne <= lastRowNum + 1; numLigne++) { Row row = sheet.getRow(numLigne - 1); String[] strs = new String[numCol]; boolean isEmptyLine = true; for (int i = 0; i < strs.length; i++) { strs[i] = getCell(row, i, df); if ((strs[i] != null) && (strs[i].length() > 0)) { isEmptyLine = false;//from w ww . j a v a 2s . c om } } if (isEmptyLine == false) { // On cre le DTO T dto = createDto(strs); // On vrifie tout d'abord si les elements de base sont bien prsents performBasicCheck(dto, numLigne); if (errorMessage.size() != 0) { return; } // On verifie ensuite si l'lment est bien compatible avec les autres lignes du fichier checkLineInSameFile(utilisateurs, dto, numLigne); if (errorMessage.size() != 0) { return; } // On verifie ensuite si l'lment est bien compatible avec les autres enregistrement de la base checkLineInDataBase(existing, dto, numLigne); if (errorMessage.size() != 0) { return; } utilisateurs.add(dto); } } saveInDataBase(utilisateurs); }
From source file:framework.retrieval.engine.index.create.impl.file.parse.ExcelFileContentParser.java
License:Apache License
public String getContent(RFileDocument document, String charsetName) { InputStream fileInputStream = null; StringBuffer content = new StringBuffer(); try {/*from w ww. j ava2 s .c o m*/ fileInputStream = new FileInputStream(document.getFile()); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);// Excel if (workbook != null) { int numSheetsNumber = workbook.getNumberOfSheets(); for (int numSheets = 0; numSheets < numSheetsNumber; numSheets++) { HSSFSheet aSheet = workbook.getSheetAt(numSheets);// sheet if (aSheet != null) { int lastRowNum = aSheet.getLastRowNum(); for (int rowNumOfSheet = 0; rowNumOfSheet <= lastRowNum; rowNumOfSheet++) { HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // if (aRow != null) { int lastCellNum = aRow.getLastCellNum(); for (int cellNumOfRow = 0; cellNumOfRow <= lastCellNum; cellNumOfRow++) { HSSFCell aCell = aRow.getCell(cellNumOfRow);// if (aCell != null) { int cellType = aCell.getCellType(); if (cellType == HSSFCell.CELL_TYPE_STRING) { String value = StringClass.getString(aCell.getStringCellValue()); content.append(value); } } } } } } } } } catch (Exception e) { RetrievalUtil.errorLog(log, document.getFile().getAbsolutePath(), e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (Exception e) { } } } return content.toString(); }
From source file:gda.hrpd.data.ExcelWorkbook.java
License:Open Source License
/** * returns the specified row from the specified sheet * /*from ww w .j a v a 2s.co m*/ * @param sheet * @param rownum * @return HSSFRow */ public HSSFRow getRow(HSSFSheet sheet, int rownum) { return sheet.getRow(rownum); }
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/*www. j a va2 s. com*/ */ 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:gov.nih.nci.cabig.caaers.dataimport.AgentSpecificTermsImporter.java
License:BSD License
public Map<String, Object> importFile() throws Exception { POIFSFileSystem poifs;//ww w. j av a 2 s . co 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; }
From source file:gov.nih.nci.evs.browser.utils.ExcelUtil.java
License:Open Source License
public static String getHSSFHeader(String file, int sheet) { StringBuffer buf = new StringBuffer(); try {//ww w . jav a2 s .c o m FileInputStream fis = new FileInputStream(new File(file)); //Get the workbook instance for XLS file HSSFWorkbook workbook = new HSSFWorkbook(fis); try { fis.close(); } catch (Exception ex) { ex.printStackTrace(); } //Get first sheet from the workbook HSSFSheet hSSFSheet = workbook.getSheetAt(sheet); HSSFRow row = hSSFSheet.getRow(0); int cells = row.getPhysicalNumberOfCells(); for (int c = 0; c < cells; c++) { HSSFCell cell = row.getCell(c); String value = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: value = cell.getCellFormula(); break; case HSSFCell.CELL_TYPE_NUMERIC: value = "" + cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; default: } buf.append(value); if (c < cells - 1) { buf.append("|"); } } } catch (Exception ex) { ex.printStackTrace(); } return buf.toString(); }
From source file:gov.nih.nci.evs.browser.utils.ResolvedValueSetIteratorHolder.java
License:Open Source License
private void table(final HSSFSheet sheet) { if (sheet == null) { return;/*from w w w . jav a 2s . co m*/ } if (sheet.getDrawingPatriarch() != null) { final List<HSSFShape> shapes = sheet.getDrawingPatriarch().getChildren(); for (int i = 0; i < shapes.size(); ++i) { if (shapes.get(i) instanceof HSSFPicture) { try { // Gain access to private field anchor. final HSSFShape pic = shapes.get(i); final Field f = HSSFShape.class.getDeclaredField("anchor"); f.setAccessible(true); final HSSFClientAnchor anchor = (HSSFClientAnchor) f.get(pic); // Store picture cell row, column and picture data. if (!pix.containsKey(anchor.getRow1())) { pix.put(anchor.getRow1(), new HashMap<Short, List<HSSFPictureData>>()); } if (!pix.get(anchor.getRow1()).containsKey(anchor.getCol1())) { pix.get(anchor.getRow1()).put(anchor.getCol1(), new ArrayList<HSSFPictureData>()); } pix.get(anchor.getRow1()).get(anchor.getCol1()) .add(book.getAllPictures().get(((HSSFPicture) pic).getPictureIndex())); } catch (final Exception e) { throw new RuntimeException(e); } } } } out.append("<table cellspacing='0' style='border-spacing:0; border-collapse:collapse;'>\n"); for (rowIndex = 0; rowIndex < sheet.getPhysicalNumberOfRows(); ++rowIndex) { tr(sheet.getRow(rowIndex)); } out.append("</table>\n"); }
From source file:gov.nih.nci.evs.browser.utils.ResolvedValueSetIteratorHolder.java
License:Open Source License
private void table(final HSSFSheet sheet, int startIndex, int endIndex) { if (sheet == null) { return;/*from www . jav a2 s.co m*/ } if (sheet.getDrawingPatriarch() != null) { final List<HSSFShape> shapes = sheet.getDrawingPatriarch().getChildren(); for (int i = 0; i < shapes.size(); ++i) { if (shapes.get(i) instanceof HSSFPicture) { try { // Gain access to private field anchor. final HSSFShape pic = shapes.get(i); final Field f = HSSFShape.class.getDeclaredField("anchor"); f.setAccessible(true); final HSSFClientAnchor anchor = (HSSFClientAnchor) f.get(pic); // Store picture cell row, column and picture data. if (!pix.containsKey(anchor.getRow1())) { pix.put(anchor.getRow1(), new HashMap<Short, List<HSSFPictureData>>()); } if (!pix.get(anchor.getRow1()).containsKey(anchor.getCol1())) { pix.get(anchor.getRow1()).put(anchor.getCol1(), new ArrayList<HSSFPictureData>()); } pix.get(anchor.getRow1()).get(anchor.getCol1()) .add(book.getAllPictures().get(((HSSFPicture) pic).getPictureIndex())); } catch (final Exception e) { throw new RuntimeException(e); } } } } out.append("<table id=\"" + "rvs_table" + "\" width=\"915\" class=\"mt\">\n"); tr(sheet.getRow(0)); StringBuffer buf = new StringBuffer(); tr(sheet.getRow(0), buf); String t = buf.toString(); resolvedValueSetList.add(t); for (int i = startIndex; i <= endIndex; i++) { tr(sheet.getRow(i)); buf = new StringBuffer(); tr(sheet.getRow(i), buf); t = buf.toString(); resolvedValueSetList.add(t); } out.append("</table>\n"); resolvedValueSetIterator = resolvedValueSetList.listIterator(); }
From source file:gov.nih.nci.evs.browser.utils.ResolvedValueSetIteratorHolder.java
License:Open Source License
private void table(final HSSFSheet sheet, int startIndex, int col, String code, boolean cdisc) { resolvedValueSetList = new ArrayList(); if (sheet == null) { return;/*from ww w.ja v a2 s. com*/ } if (sheet.getDrawingPatriarch() != null) { final List<HSSFShape> shapes = sheet.getDrawingPatriarch().getChildren(); for (int i = 0; i < shapes.size(); ++i) { if (shapes.get(i) instanceof HSSFPicture) { try { // Gain access to private field anchor. final HSSFShape pic = shapes.get(i); final Field f = HSSFShape.class.getDeclaredField("anchor"); f.setAccessible(true); final HSSFClientAnchor anchor = (HSSFClientAnchor) f.get(pic); // Store picture cell row, column and picture data. if (!pix.containsKey(anchor.getRow1())) { pix.put(anchor.getRow1(), new HashMap<Short, List<HSSFPictureData>>()); } if (!pix.get(anchor.getRow1()).containsKey(anchor.getCol1())) { pix.get(anchor.getRow1()).put(anchor.getCol1(), new ArrayList<HSSFPictureData>()); } pix.get(anchor.getRow1()).get(anchor.getCol1()) .add(book.getAllPictures().get(((HSSFPicture) pic).getPictureIndex())); } catch (final Exception e) { throw new RuntimeException(e); } } } } out.append("<table id=\"" + "rvs_table" + "\" width=\"915\" class=\"mt\">\n"); tr(sheet.getRow(0)); StringBuffer buf = new StringBuffer(); tr(sheet.getRow(0), buf); String t = buf.toString(); resolvedValueSetList.add(t); int rows = sheet.getPhysicalNumberOfRows(); for (int i = startIndex; i <= rows; i++) { HSSFRow row = sheet.getRow(i); if (row != null) { if (col != -1) { HSSFCell cell = row.getCell(col); if (cell != null) { String value = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: value = cell.getCellFormula(); break; case HSSFCell.CELL_TYPE_NUMERIC: value = "" + cell.getNumericCellValue(); break; case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; default: } if ((cdisc && i == startIndex) || (value != null && value.compareTo(code) == 0)) { tr(row); buf = new StringBuffer(); tr(row, buf); t = buf.toString(); resolvedValueSetList.add(t); } } } else { tr(row); buf = new StringBuffer(); tr(row, buf); t = buf.toString(); resolvedValueSetList.add(t); } } } out.append("</table>\n"); resolvedValueSetIterator = resolvedValueSetList.listIterator(); }