List of usage examples for org.apache.poi.ss.usermodel Cell getColumnIndex
int getColumnIndex();
From source file:ru.icc.cells.ssdc.DataLoader.java
License:Apache License
public CTable nextTable() { if (null == sheet) throw new IllegalStateException("The sheet is not initialized"); CPoint refPnt = findRefPoint(sheet, rowIndex); if (null == refPnt) return null; CPoint endPnt = findEndPoint(sheet, refPnt.r); if (null == endPnt) return null; int numOfCols = endPnt.c - refPnt.c + 1; int numOfRows = endPnt.r - refPnt.r + 1; CTable table = new CTable(numOfRows, numOfCols); //CCell cell; Cell excelCell; Row row = null;/*from w w w . j a v a 2 s .c o m*/ CellRangeAddress cellRangeAddress = null; boolean isCell = false; int refRowAdr = refPnt.r; int endRowAdr = endPnt.r; int refColAdr = refPnt.c; int endColAdr = endPnt.c; for (int i = refRowAdr; i <= endRowAdr; i++) { row = sheet.getRow(i); // TODO ?? ? ?, r == null if (null == row) continue; for (int j = refColAdr; j <= endColAdr; j++) { // TODO ?? ? ?, excelCell == null excelCell = row.getCell(j, Row.CREATE_NULL_AS_BLANK); int colAdr = excelCell.getColumnIndex() - refColAdr + 1; int rowAdr = excelCell.getRowIndex() - refRowAdr + 1; int cl = colAdr; int cr = colAdr; int rt = rowAdr; int rb = rowAdr; isCell = true; for (int k = 0; k < sheet.getNumMergedRegions(); k++) { cellRangeAddress = sheet.getMergedRegion(k); if (cellRangeAddress.getFirstColumn() == excelCell.getColumnIndex() && cellRangeAddress.getFirstRow() == excelCell.getRowIndex()) { cr = cellRangeAddress.getLastColumn() - refColAdr + 1; rb = cellRangeAddress.getLastRow() - refRowAdr + 1; break; } if (cellRangeAddress.getFirstColumn() <= excelCell.getColumnIndex() && excelCell.getColumnIndex() <= cellRangeAddress.getLastColumn() && cellRangeAddress.getFirstRow() <= excelCell.getRowIndex() && excelCell.getRowIndex() <= cellRangeAddress.getLastRow()) { isCell = false; } } if (isCell) { CCell cell = table.newCell(); cell.setCl(cl); cell.setRt(rt); cell.setCr(cr); cell.setRb(rb); fillCell(cell, excelCell); } } } this.rowIndex = endPnt.r + 1; // ? /* CPoint namePnt = this.findPreviousPoint( this.sheet, TBL_NAME, refPnt.r - 1 ); if ( null != namePnt ) { row = sheet.getRow( namePnt.r); //excelCell = r.getCell( namePnt.c + 1 ); excelCell = row.getCell( namePnt.c + 1, Row.CREATE_NULL_AS_BLANK ); String name = extractCellValue( excelCell ); //table.getContext().setName( name ); } CPoint measurePnt = this.findPreviousPoint( this.sheet, TBL_MEASURE, refPnt.r - 1 ); if ( null != measurePnt ) { row = sheet.getRow( measurePnt.r); //excelCell = r.getCell( measurePnt.c + 1 ); excelCell = row.getCell( measurePnt.c + 1, Row.CREATE_NULL_AS_BLANK ); String measure = extractCellValue( excelCell ); //table.getContext().setMeasure( measure ); } */ table.setSrcWorkbookFile(sourceWorkbookFile); table.setSrcSheetName(sheet.getSheetName()); CellReference cellRef; cellRef = new CellReference(refPnt.r, refPnt.c); table.setSrcStartCellRef(cellRef.formatAsString()); cellRef = new CellReference(endPnt.r, endPnt.c); table.setSrcEndCellRef(cellRef.formatAsString()); return table; }
From source file:ru.icc.cells.ssdc.DataLoader.java
License:Apache License
private CPoint findPreviousPoint(Sheet sheet, String tag, int startRow) { for (int i = startRow; i > -1; i--) { Row row = sheet.getRow(i);/*from w ww. j av a 2 s . c o m*/ if (null == row) continue; for (Cell cell : row) { String text = getFormatCellValue(cell); if (tag.equals(text)) return new CPoint(cell.getColumnIndex(), cell.getRowIndex()); } } return null; }
From source file:ru.icc.cells.ssdc.DataLoader.java
License:Apache License
private CPoint findNextPoint(Sheet sheet, String tag, int startRow) { for (int i = startRow; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i);// ww w. ja va 2 s .c om if (null == row) continue; for (Cell cell : row) { String text = getFormatCellValue(cell); if (tag.equals(text)) return new CPoint(cell.getColumnIndex(), cell.getRowIndex()); } } return null; }
From source file:ru.icc.cells.ssdc.DataLoader.java
License:Apache License
private void fillCell(CCell cell, Cell excelCell) { String rawTextualContent = null; CellType cellType = null;/*from w ww .j a va 2s . com*/ String text = null; if (withoutSuperscript) { if (hasSuperscriptText(excelCell)) { text = getNotSuperscriptText(excelCell); } else { text = getText(excelCell); } } else { text = getText(excelCell); } cell.setText(text); rawTextualContent = getFormatCellValue(excelCell); cell.setRawText(rawTextualContent); switch (excelCell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(excelCell)) { //rawTextualContent = "DATE"; // TODO - ? cellType = CellType.DATE; } else { cellType = CellType.NUMERIC; } break; case Cell.CELL_TYPE_STRING: cellType = CellType.STRING; break; case Cell.CELL_TYPE_BOOLEAN: cellType = CellType.BOOLEAN; break; case Cell.CELL_TYPE_FORMULA: cellType = CellType.FORMULA; break; case Cell.CELL_TYPE_BLANK: cellType = CellType.BLANK; break; case Cell.CELL_TYPE_ERROR: cellType = CellType.ERROR; break; } cell.setId(this.cellCount); cell.setCellType(cellType); int height = excelCell.getRow().getHeight(); cell.setHeight(height); int width = excelCell.getSheet().getColumnWidth(excelCell.getColumnIndex()); cell.setWidth(width); CellStyle excelCellStyle = excelCell.getCellStyle(); CStyle cellStyle = cell.getStyle(); fillCellStyle(cellStyle, excelCellStyle); String reference = new CellReference(excelCell).formatAsString(); cell.setProvenance(reference); this.cellCount++; }
From source file:se.sll.invoicedata.price.GeneratePriceList.java
License:Open Source License
private List<String> getServicePrice(Sheet sheet, int startRow, int serviceType) { FormulaEvaluator formulaEval = sheet.getWorkbook().getCreationHelper().createFormulaEvaluator(); List<String> priceList = new ArrayList<String>(); for (int i = startRow; i < sheet.getPhysicalNumberOfRows(); i++) { Cell cell = sheet.getRow(i).getCell(serviceType); if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: priceList.add(DECIMAL_FORMAT.format(cell.getNumericCellValue())); break; case Cell.CELL_TYPE_FORMULA: double d = formulaEval.evaluate(cell).getNumberValue(); priceList.add(DECIMAL_FORMAT.format(d)); break; case Cell.CELL_TYPE_BLANK: priceList.add(DECIMAL_FORMAT.format(0)); break; default: StringBuffer errorMsg = new StringBuffer("This type of cell is not handled by the program!"); errorMsg.append(" cell type:").append(cell.getCellType()); errorMsg.append(" cell row:").append(cell.getRowIndex()); errorMsg.append(" cell column:").append(cell.getColumnIndex()); errorMsg.append(" cell value:").append(cell.getStringCellValue()); throw new IllegalStateException(errorMsg.toString()); }//from w w w . ja va 2s. c o m } else { priceList.add(DECIMAL_FORMAT.format(0)); } } return priceList; }
From source file:se.softhouse.garden.oak.ExcelDecisionTableBuilder.java
License:Open Source License
private Number getNumericValue(int type, Cell cell) { switch (type) { case Cell.CELL_TYPE_NUMERIC: if (cell instanceof XSSFCell) { String raw = ((XSSFCell) cell).getRawValue(); return new BigDecimal(raw); }//from www. j a v a 2s . com return cell.getNumericCellValue(); case Cell.CELL_TYPE_FORMULA: return getNumericValue(cell.getCachedFormulaResultType(), cell); case Cell.CELL_TYPE_STRING: { String raw = cell.getStringCellValue(); if (raw == null || raw.isEmpty() || !raw.matches("0-9")) { // We throw this instead of the plain NumberFormatException that would've been // thrown otherwise. throw new IllegalArgumentException("Invalid Numeric String Cell value [" + raw + "] in Sheet(" + cell.getSheet().getSheetName() + "). Row:Column[" + cell.getRowIndex() + 1 + ":" + (cell.getColumnIndex() + 1) + "]"); } return new BigDecimal(raw); } } return BigDecimal.ZERO; }
From source file:servlets.UploadAccountingServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TEST"); InputStream inputStream = null; Part filePart = request.getPart("file"); inputStream = filePart.getInputStream(); POIFSFileSystem fs = new POIFSFileSystem(inputStream); // FileInputStream fichier = new FileInputStream(new File("countries.xls")); //create workbook instance that refers to xlsx file HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0);/*ww w. j a v a 2s. c o m*/ FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); ArrayList<Accounting> arrAccounting = new ArrayList<>(); ReportDB reportDB = new ReportDB(); reportDB.addReport(new Report("Accounting", "Pending")); ArrayList<Report> reportList = new ArrayList(); reportList = reportDB.getAllReports(); int ReportRef = reportList.size(); for (Row ligne : sheet) {//iterate rows Accounting accounting = new Accounting(); for (Cell cell : ligne) {//iterate columns //cell type /* Sales sales; (lagay sa sys out) sales.setSalesID(cell.getNumericCellValue()); --- WALA TO */ switch (formulaEvaluator.evaluateInCell(cell).getCellType()) { case Cell.CELL_TYPE_NUMERIC: // sales.setName(cell.getNumericCellValue()); System.out.print("cell 1 " + cell.getNumericCellValue() + " \t"); if (cell.getColumnIndex() == 1) { accounting.setPoNo((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 4) { accounting.setAgingDays((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 5) { accounting.setCustomerID((int) cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: System.out.print("cell 2 " + cell.getStringCellValue() + " \t"); if (cell.getColumnIndex() == 0) { accounting.setStartDate(cell.getStringCellValue()); } if (cell.getColumnIndex() == 2) { accounting.setTerms(cell.getStringCellValue()); } if (cell.getColumnIndex() == 3) { accounting.setDueDate(cell.getStringCellValue()); } break; } } accounting.setReportRef(ReportRef); arrAccounting.add(accounting); System.out.println(); } request.setAttribute("arrAccounting", arrAccounting); AccountingDB accountingDB = new AccountingDB(); request.setAttribute("arrAccounting", arrAccounting); for (int j = 0; j < arrAccounting.size(); j++) { accountingDB.addAccounting(arrAccounting.get(j)); } ServletContext context = getServletContext(); RequestDispatcher rd = context.getRequestDispatcher("/isrAfteruploadAccounting.jsp"); rd.forward(request, response); processRequest(request, response); }
From source file:servlets.UploadInventoryServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TEST"); InputStream inputStream = null; Part filePart = request.getPart("file"); inputStream = filePart.getInputStream(); POIFSFileSystem fs = new POIFSFileSystem(inputStream); // FileInputStream fichier = new FileInputStream(new File("countries.xls")); //create workbook instance that refers to xlsx file HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0);/*from w w w . j a va 2 s.c o m*/ FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); ArrayList<Inventory> arrInventory = new ArrayList<>(); ReportDB reportDB = new ReportDB(); reportDB.addReport(new Report("Inventory", "Pending")); ArrayList<Report> reportList = new ArrayList(); reportList = reportDB.getAllReports(); int ReportRef = reportList.size(); for (Row ligne : sheet) {//iterate rows Inventory inventory = new Inventory(); for (Cell cell : ligne) {//iterate columns //cell type /* Sales sales; (lagay sa sys out) sales.setSalesID(cell.getNumericCellValue()); --- WALA TO */ switch (formulaEvaluator.evaluateInCell(cell).getCellType()) { case Cell.CELL_TYPE_NUMERIC: // sales.setName(cell.getNumericCellValue()); System.out.print("cell 1 " + cell.getNumericCellValue() + " \t"); if (cell.getColumnIndex() == 1) { inventory.setQuantityOnHand((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 2) { inventory.setGrandTotal((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 3) { inventory.setBatchNo((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 6) { inventory.setAvemonTO(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: System.out.print("cell 2 " + cell.getStringCellValue() + " \t"); if (cell.getColumnIndex() == 0) { inventory.setBrandName(cell.getStringCellValue()); } if (cell.getColumnIndex() == 4) { inventory.setExpDate(cell.getStringCellValue()); } if (cell.getColumnIndex() == 5) { inventory.setShelfLife(cell.getStringCellValue()); } if (cell.getColumnIndex() == 7) { inventory.setInventoryMonths(cell.getStringCellValue()); } break; } } inventory.setReportRef(ReportRef); arrInventory.add(inventory); System.out.println(); } request.setAttribute("arrInventory", arrInventory); InventoryDB inventoryDB = new InventoryDB(); request.setAttribute("arrInventory", arrInventory); for (int j = 0; j < arrInventory.size(); j++) { inventoryDB.addInventory(arrInventory.get(j)); } ServletContext context = getServletContext(); RequestDispatcher rd = context.getRequestDispatcher("/isrAfteruploadInventory.jsp"); rd.forward(request, response); processRequest(request, response); }
From source file:servlets.UploadSalesServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w . jav a 2 s .c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TEST"); InputStream inputStream = null; Part filePart = request.getPart("file"); inputStream = filePart.getInputStream(); POIFSFileSystem fs = new POIFSFileSystem(inputStream); // FileInputStream fichier = new FileInputStream(new File("countries.xls")); //create workbook instance that refers to xlsx file HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); ArrayList<Sales> arrSales = new ArrayList<>(); ReportDB reportDB = new ReportDB(); reportDB.addReport(new Report("Sales", "Pending")); ArrayList<Report> reportList = new ArrayList(); reportList = reportDB.getAllReports(); int ReportRef = reportList.size(); for (Row ligne : sheet) {//iterate rows Sales sales = new Sales(); for (Cell cell : ligne) {//iterate columns //cell type switch (formulaEvaluator.evaluateInCell(cell).getCellType()) { case Cell.CELL_TYPE_NUMERIC: // sales.setName(cell.getNumericCellValue()); System.out.print("cell 1 " + cell.getNumericCellValue() + " \t"); if (cell.getColumnIndex() == 0) { sales.setSalesAmmount(cell.getNumericCellValue()); } if (cell.getColumnIndex() == 1) { sales.setCreatedBy((int) cell.getNumericCellValue()); } if (cell.getColumnIndex() == 2) { sales.setLocation((int) cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: System.out.print("cell 2 " + cell.getStringCellValue() + " \t"); break; } } sales.setReportRef(ReportRef); arrSales.add(sales); System.out.println(); } System.out.println("\t"); System.out.println("Size: " + arrSales.size()); System.out.println("\t"); for (int i = 0; i < arrSales.size(); i++) { System.out.println("Amount: " + arrSales.get(i).getSalesAmmount()); System.out.println("Created By: " + arrSales.get(i).getCreatedBy()); System.out.println("Location: " + arrSales.get(i).getLocation()); System.out.println("ReportRef: " + arrSales.get(i).getReportRef()); System.out.println("\t"); } request.setAttribute("arrSales", arrSales); SalesDB salesdb = new SalesDB(); request.setAttribute("arrSales", arrSales); for (int j = 0; j < arrSales.size(); j++) { salesdb.addSales(arrSales.get(j)); } ServletContext context = getServletContext(); RequestDispatcher rd = context.getRequestDispatcher("/isrAfteruploadSales.jsp"); rd.forward(request, response); processRequest(request, response); }
From source file:sqlitemanager.Excel2Dataset.java
public static List<DataTable> readExcel(String inPath, boolean hasIntColumns, int colsHasInt) { List<DataTable> out = new ArrayList(); try {/*from w w w. ja v a 2 s .c om*/ // Create a work book reference Workbook workbook = null; if (inPath.endsWith(".xls")) { workbook = new HSSFWorkbook(new FileInputStream(inPath)); } else if (inPath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(new FileInputStream(inPath)); } else { System.err.println("No XLS or XLSX file found!"); return out; } //Create a count of the sheets in the file short sheetsCount = (short) workbook.getNumberOfSheets(); //create a reference of sheet, cell, first head, last head, head name, //sheet name, row count and row content Sheet sheet; Row row; Cell cell; int firstIndex = Integer.MIN_VALUE; int lastIndex = Integer.MAX_VALUE; String[] headName; fieldType[] fieldTypes; String sheetName; int rowCount; Object cellValue; for (int i = 0; i < sheetsCount; i++) { sheetName = workbook.getSheetName(i); try { sheet = workbook.getSheetAt(i); rowCount = sheet.getLastRowNum() + 1; if (rowCount < 1) { break; } // row = sheet.getRow(0); // for (int j = 0; j < rowCount; j++) { // row = sheet.getRow(j); // if (firstIndex < row.getFirstCellNum()) { // firstIndex = row.getFirstCellNum(); // } // if (lastIndex > row.getLastCellNum()) { // lastIndex = row.getLastCellNum(); // } // } row = sheet.getRow(0); // Head row firstIndex = row.getFirstCellNum(); lastIndex = row.getLastCellNum(); headName = new String[lastIndex]; fieldTypes = new fieldType[lastIndex]; List<String> names = new ArrayList(); for (int index = firstIndex; index < lastIndex; index++) { String name = row.getCell(index).toString(); if (names.contains(name)) { JOptionPane.showMessageDialog(null, String.format("Field \"%s\" duplicated!", name), "Notice", JOptionPane.ERROR_MESSAGE); return null; } else { names.add(name); } headName[index] = name; fieldTypes[index] = fieldType.Double; } // Detect field types for (int k = 1; k < rowCount; k++) { row = sheet.getRow(k); if (row == null) { break; } for (int index = firstIndex; index < lastIndex; index++) { if (fieldTypes[index] != fieldType.String) { if (row.getCell(index) != null) { fieldTypes[index] = fieldType .getType(getCellType(row.getCell(index).getCellType())); } else { fieldTypes[index] = fieldType.String; } } } } DataTable tempTable = new DataTable(sheetName); for (int index = firstIndex; index < lastIndex; index++) { tempTable.addField(headName[index], fieldTypes[index]); } for (int k = 1; k < rowCount; k++) { row = sheet.getRow(k); if (row == null) { break; } tempTable.addRecord(); for (int index = firstIndex; index < lastIndex; index++) { cell = row.getCell(index); if (fieldTypes[index] == fieldType.Double) { try { cellValue = cell.getNumericCellValue(); } catch (Exception e) { System.err.println(String.format("Error reading Sheet: %s, Row: %d, Column: %d", cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex())); cellValue = cell.getStringCellValue().trim(); } } else if (fieldTypes[index] == fieldType.Integer) { try { cellValue = (int) cell.getNumericCellValue(); } catch (Exception e) { System.err.println(String.format("Error reading Sheet: %s, Row: %d, Column: %d", cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex())); cellValue = cell.getStringCellValue().trim(); } } else { if (cell == null) { cellValue = ""; } else { try { try { cellValue = cell.getNumericCellValue(); } catch (Exception e) { cellValue = cell.getStringCellValue().trim(); } } catch (Exception e) { System.err.println( String.format("Error reading Sheet: %s, Row: %d, Column: %d", cell.getSheet().getSheetName(), cell.getRowIndex(), cell.getColumnIndex())); cellValue = cell.getNumericCellValue(); } } } tempTable.getField(index).set(tempTable.getRecordCount() - 1, cellValue); } } if (hasIntColumns) { DataTable table = new DataTable(tempTable.getName()); List<Integer> updateFields = new ArrayList(); if (colsHasInt < 1) { // 0 or negative means check all columns colsHasInt = tempTable.getRecordCount(); } int cols4Check = Math.min(colsHasInt, tempTable.getRecordCount()); for (int j = 0; j < cols4Check; j++) { Field f = tempTable.getField(j); if (f.getType() != fieldType.Double) { continue; } boolean isIntColumn = true; for (int recNum = 0; recNum < tempTable.getRecordCount(); recNum++) { double value = Double.valueOf(f.get(recNum).toString()); double checkValue = Double.valueOf(String.valueOf((int) value)); if (value != checkValue) { isIntColumn = false; break; } } if (isIntColumn) { updateFields.add(j); } } for (int j = 0; j < tempTable.getFieldCount(); j++) { fieldType type = tempTable.getField(j).getType(); if (updateFields.contains(j)) { type = fieldType.Integer; } table.addField(tempTable.getField(j).getName(), type); } for (int recNum = 0; recNum < tempTable.getRecordCount(); recNum++) { table.addRecord(); for (int col = 0; col < tempTable.getFieldCount(); col++) { Object rowItem; if (updateFields.contains(col)) { Double value = (double) tempTable.getRecord(recNum).get(col); rowItem = value.intValue(); } else { rowItem = tempTable.getRecord(recNum).get(col); } table.getField(col).set(table.getRecordCount() - 1, rowItem); } } out.add(table); } else { out.add(tempTable); } } catch (Exception e) { Logger.getLogger(Excel2Dataset.class.getName()).log(Level.SEVERE, null, e); JOptionPane.showMessageDialog(null, String.format("Loading sheet %s error!", sheetName), "Notice", JOptionPane.ERROR_MESSAGE); } } } catch (Exception ex) { Logger.getLogger(Excel2Dataset.class.getName()).log(Level.SEVERE, null, ex); } return out; }