List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet getRow
@Override public XSSFRow getRow(int rownum)
From source file:com.cms.utils.DataUtil.java
License:Open Source License
/** * * @param file/*from ww w .j ava 2s .c o m*/ * @param iSheet * @param iBeginRow * @param iFromCol * @param iToCol * @param rowBack * @param lstValidateCells * @return */ public static List isValidExcells(String mimeType, File file, int iSheet, int iBeginRow, int iFromCol, int iToCol, int rowBack, List<ValidateCells> lstValidateCells) { String fileName = file.getName(); fileName = removeDotInteger(fileName); boolean isCopySheet = true; File fileError = null; Map<String, String> mapsNameError = new HashMap<>(); List lst = null; try { if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLSX)) { // xlsx lst = ExcelReaderXLSX.importExcel(file, iSheet, iBeginRow, iFromCol, iToCol, rowBack); } else if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLS)) { // xls lst = ExcelReader.importExcel(file, iSheet, iBeginRow, iFromCol, iToCol, rowBack); } //If lst null return if (lst == null) { return lst; } String error = ""; ValidateCells validateCells = null; int index = 0; if (iBeginRow == 0) { index = 1; } else { index = 0; } int rowErr = 0; Object[] temp; List<String> lstReturn = Lists.newArrayList(); for (int i = index, size = lst.size(); i < size; i++) { temp = (Object[]) lst.get(i); if (checkObjectNull(temp)) { // lst.remove(temp); // i--; // continue; if (i == 0) { lst = Lists.newArrayList(); } break; } error = ""; for (int j = 0; j < lstValidateCells.size(); j++) { validateCells = lstValidateCells.get(j); if (validateCells.getPattern() != null) { error += DataUtil.validCell(i, j, (String) temp[j], validateCells.getType(), validateCells.isIsNotNull(), validateCells.getPattern()); } else { lstReturn = DataUtil.validCell(i, j, (String) temp[j], validateCells.getType(), validateCells.isIsNotNull(), validateCells.getLength()); error += lstReturn.get(0); temp[j] = lstReturn.get(1); } } if (!isStringNullOrEmpty(error)) { rowErr = i + iBeginRow; mapsNameError.put(rowErr + "", error); } } if (!mapsNameError.isEmpty()) { // FileInputStream flieInput = new FileInputStream(file); XSSFWorkbook workbookIp = null; String fileCreate = fileName + "_Error.xlsx"; FileOutputStream fileOut = new FileOutputStream(fileCreate); XSSFWorkbook workbookEp = new XSSFWorkbook(); XSSFSheet worksheetEp = workbookEp.createSheet("Thong_Tin_Loi"); XSSFCellStyle cellStyle = null; // if (isCopySheet) { if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLSX)) { // xlsx workbookIp = new XSSFWorkbook(flieInput); } else if (mimeType.equalsIgnoreCase(Constants.FORMATFILE.EXCEL_XLS)) { // xls HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(flieInput); workbookIp = ExcelReaderXLSX.convertWorkbookHSSFToXSSF(hSSFWorkbook); } XSSFSheet worksheetIp = workbookIp.getSheetAt(iSheet); ExcelReaderXLSX.copySheets(worksheetEp, worksheetIp, iToCol); // cellStyle = CommonUtils.styleCell(workbookEp); isCopySheet = false; } for (Map.Entry<String, String> entrySet : mapsNameError.entrySet()) { String key = entrySet.getKey(); String value = entrySet.getValue(); int row = Integer.valueOf(key); XSSFRow row5 = worksheetEp.getRow(row); if (row5 != null) { XSSFCell cellB1 = row5.createCell(iToCol + 1); cellB1.setCellValue(value); cellB1.setCellStyle(cellStyle); } } workbookEp.write(fileOut); fileOut.flush(); fileOut.close(); fileError = new File(fileCreate); Resource resource = new FileResource(fileError); Page.getCurrent().open(resource, null, false); lst = null; fileError.deleteOnExit(); } } catch (Exception e) { e.printStackTrace(); ; lst = null; } return lst; }
From source file:com.cn.util.ExcelImport.java
/** * ?2007excel// w w w . ja va2 s . co m * * @param file * @return */ private static List<List<Object>> read2007Excel(InputStream inputStream) throws IOException { List<List<Object>> dataList = new ArrayList<>(); XSSFWorkbook xwb = new XSSFWorkbook(inputStream); XSSFSheet sheet = xwb.getSheetAt(0); XSSFRow row = null; XSSFCell cell = null; Object val = null; DecimalFormat df = new DecimalFormat("0");// ? SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ? for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); if (row == null) { continue; } List<Object> objList = new ArrayList<>(); for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) { cell = row.getCell(j); if (cell == null) { val = null; objList.add(val); continue; } switch (cell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: val = cell.getStringCellValue(); break; case XSSFCell.CELL_TYPE_NUMERIC: if ("@".equals(cell.getCellStyle().getDataFormatString())) { val = df.format(cell.getNumericCellValue()); } else if ("General".equals(cell.getCellStyle().getDataFormatString())) { val = df.format(cell.getNumericCellValue()); } else { val = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())); } break; case XSSFCell.CELL_TYPE_BOOLEAN: val = cell.getBooleanCellValue(); break; case XSSFCell.CELL_TYPE_BLANK: val = ""; break; default: val = cell.toString(); break; } objList.add(val); } dataList.add(objList); } return dataList; }
From source file:com.codequicker.quick.templates.source.adapters.ExcelSourceAdapter.java
License:Apache License
private void readXmlBasedExcel(BufferedInputStream bufferedStream, Map<String, List<Map<String, String>>> data) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(bufferedStream); int sheetCount = workbook.getNumberOfSheets(); for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) { XSSFSheet sheet = workbook.getSheetAt(sheetIndex); Cell cell = null;//from w w w . j av a 2 s. c om List<Map<String, String>> sheetData = new ArrayList<Map<String, String>>(); int lastRowNumber = sheet.getLastRowNum(); for (int rowIndex = 0; rowIndex <= lastRowNumber; rowIndex++) { XSSFRow row = sheet.getRow(rowIndex); if (row == null) { continue; } Map<String, String> columnData = new HashMap<String, String>(); for (int cellIndex = 0; cellIndex < row.getLastCellNum(); cellIndex++) { cell = row.getCell(cellIndex, Row.CREATE_NULL_AS_BLANK); columnData.put("column" + (cellIndex + 1), cell.toString()); } sheetData.add(columnData); } data.put("sheet" + (sheetIndex + 1), sheetData); } }
From source file:com.codesnippets4all.jthunder.extension.plugins.input.excel.ExcelReaderPlugin.java
License:Apache License
@SuppressWarnings("rawtypes") private void readXmlBasedExcel(BufferedInputStream bufferedStream, List<Sheet> sheets) throws IOException { XSSFWorkbook workbook = new XSSFWorkbook(bufferedStream); int sheetCount = workbook.getNumberOfSheets(); for (int index = 0; index < sheetCount; index++) { XSSFSheet sheet = workbook.getSheetAt(index); Sheet s = new Sheet(); sheets.add(s);//from ww w . ja v a 2s . c o m int lastRowNumber = sheet.getLastRowNum(); for (int rowIndex = 0; rowIndex < lastRowNumber; rowIndex++) { XSSFRow row = sheet.getRow(rowIndex); Record record = new Record(); s.addRecord(record); Iterator it = row.cellIterator(); while (it.hasNext()) { record.addCellValue(it.next()); } } } }
From source file:com.consensus.qa.framework.ExcelOperations.java
public String GetSimType(FileNames fileName, SheetName sheetName) throws IOException { String filePath = FilePath(fileName); String simType = null;/*from ww w .ja v a 2 s. c o m*/ try { String sheet = sheetName.toString(); if (sheetName.toString().contains("_")) { String[] Name = sheetName.toString().split("_"); sheet = Name[1]; } SetStatusForSimTypSheets(sheet, fileName); fileInput = new FileInputStream(new File(filePath)); workBook = new XSSFWorkbook(fileInput); XSSFSheet workSheet = workBook.getSheet(sheet); for (int i = 0; i < workSheet.getPhysicalNumberOfRows(); i++) { Row currentRow = workSheet.getRow(i); int type = 1; Cell cell = currentRow.getCell(1); try { type = cell.getCellType(); System.out.println(type); System.out.println(workSheet.getRow(i).getCell(1).toString()); System.out.println(cell.getStringCellValue().toLowerCase()); if (type == 1 && cell.getStringCellValue().toLowerCase() .equals(Status.UNUSED.toString().toLowerCase())) { cell.setCellValue(Status.INUSE.toString()); simType = currentRow.getCell(0).getStringCellValue(); break; } } catch (Exception e) { if (type != 1) { cell = currentRow.createCell(1); cell.setCellValue(Status.UNUSED.toString()); } } } } catch (Exception ex) { Log.error(ex.toString()); } finally { WriteAndCloseFile(filePath, fileInput, workBook); } return simType; }
From source file:com.consensus.qa.framework.ExcelOperations.java
public void SetStatusForSimTypSheets(String sheet, FileNames fileName) throws IOException { int statusColumn; XSSFSheet workSheet = null; String filePath = FilePath(fileName); fileInput = new FileInputStream(new File(filePath)); workBook = GetWorkBook(fileName);//from w ww . java 2 s. c o m for (int i = 0; i < workBook.getNumberOfSheets(); i++) { if (workBook.getSheetName(i).toLowerCase().contains(sheet.toLowerCase())) { workSheet = workBook.getSheetAt(i); break; } } try { for (int i = 0; i < workSheet.getPhysicalNumberOfRows(); i++) { Row statusRow = workSheet.getRow(i); for (int ct = 0; ct < statusRow.getPhysicalNumberOfCells(); ct++) { System.out.println(statusRow.getCell(ct)); } int numOfCells = statusRow.getPhysicalNumberOfCells(); if (workSheet.getRow(i).getCell(numOfCells - 1).getStringCellValue().toUpperCase() .contains(Status.STATUS.toString()) || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase() .contains(Status.UNUSED.toString()) || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase() .contains(Status.INUSE.toString()) || workSheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase() .contains(Status.USED.toString())) { statusColumn = numOfCells - 1; } else { statusColumn = numOfCells; Cell statusCell = workSheet.getRow(i).createCell(statusColumn); statusCell.setCellValue(Status.UNUSED.toString()); continue; } System.out.println(statusRow.getCell(statusColumn)); try { if (statusRow.getCell(statusColumn) == null) { Cell cell = row.createCell(statusColumn); cell.setCellValue(Status.UNUSED.toString()); } } catch (Exception ex) { row.createCell(statusColumn).setCellValue(Status.UNUSED.toString()); } } } catch (Exception ex) { Log.error(ex.toString()); } finally { WriteAndCloseFile(filePath, fileInput, workBook); } }
From source file:com.consensus.qa.framework.ExcelOperations.java
@SuppressWarnings("unused") public AccountDetails GetAccountDetails(FileNames fileName, SheetName worksheetName) throws IOException { String filePath = FilePath(fileName); fileInput = new FileInputStream(new File(filePath)); workBook = new XSSFWorkbook(fileInput); XSSFSheet workSheet = GetSheetFromWorkBook(workBook, worksheetName.toString()); AccountDetails accountDetails = new AccountDetails(); try {//from www . j a va 2 s.c om int mtnIndex = -1; int passwordIndex = -1; int ssnIndex = -1; int statusCol = -1; Row row = workSheet.getRow(0); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (String.valueOf(cell.getStringCellValue()).contains("MTN")) { mtnIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains("Password")) { passwordIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains("SSN")) { ssnIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains(Status.STATUS.toString())) { statusCol = cell.getColumnIndex(); } if (mtnIndex != -1 && passwordIndex != -1 && ssnIndex != -1 && statusCol != -1) { break; } } if (statusCol == -1) { statusCol = (workSheet.getRow(0).getPhysicalNumberOfCells()); Cell cell = workSheet.getRow(0).createCell(statusCol); cell.setCellValue(Status.STATUS.toString()); } for (int i = 1; i < workSheet.getPhysicalNumberOfRows(); i++) { Cell cell = null; if (workSheet.getRow(i).getCell(statusCol) == null || (workSheet.getRow(i).getCell(statusCol).getCellType() == Cell.CELL_TYPE_BLANK)) { cell = workSheet.getRow(i).createCell(statusCol); cell.setCellValue(Status.UNUSED.toString()); } cell = workSheet.getRow(i).getCell(statusCol); if (cell.getStringCellValue().toString().equals(Status.UNUSED.toString())) { accountDetails.MTN = String .valueOf(workSheet.getRow(i).getCell(mtnIndex).getNumericCellValue()); accountDetails.Password = workSheet.getRow(i).getCell(passwordIndex).getStringCellValue(); accountDetails.SSN = String .valueOf(workSheet.getRow(i).getCell(ssnIndex).getNumericCellValue()); cell.setCellValue(Status.INUSE.toString()); break; } } } catch (Exception ex) { ex.printStackTrace(); } finally { WriteAndCloseFile(filePath, fileInput, workBook); } if (accountDetails == null) Log.error("FAILED To get account details; one among MTN/Password/SSN is blank"); return accountDetails; }
From source file:com.consensus.qa.framework.ExcelOperations.java
public int CreateStatusColumn(String filePath, String workSheetName) throws IOException { //String filePath = FilePath(fileName); fileInput = new FileInputStream(new File(filePath)); workBook = new XSSFWorkbook(fileInput); XSSFSheet worksheet = GetSheetFromWorkBook(workBook, workSheetName); int statusColumn = -1; try {/*from w ww . j a v a2s. c om*/ for (int i = 0; i < worksheet.getPhysicalNumberOfRows(); i++) { row = worksheet.getRow(i); if (i == 0) { int numOfCells = row.getPhysicalNumberOfCells(); if (worksheet.getRow(0).getCell(numOfCells - 1).getStringCellValue().toUpperCase() .contains(Status.STATUS.toString())) { statusColumn = numOfCells - 1; } else { statusColumn = numOfCells; Cell statusCell = row.createCell(statusColumn); statusCell.setCellValue(Status.STATUS.toString()); continue; } } if (row.getCell(statusColumn) == null) { Cell cell = row.createCell(statusColumn); cell.setCellValue(Status.UNUSED.toString()); } } } catch (Exception ex) { ex.printStackTrace(); } return statusColumn; }
From source file:com.consensus.qa.framework.ExcelOperations.java
@SuppressWarnings("unused") public NPANXX GetNumberPortData(FileNames fileName, SheetName workSheetName) throws IOException { String filePath = FilePath(fileName); fileInput = new FileInputStream(new File(filePath)); workBook = new XSSFWorkbook(fileInput); XSSFSheet workSheet = GetSheetFromWorkBook(workBook, workSheetName.toString()); NPANXX npaNXX = new NPANXX(); try {//from w w w . j av a 2 s . c om int mtnIndex = -1; int passwordIndex = -1; int ssnIndex = -1; int statusCol = -1; Row row = workSheet.getRow(0); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (String.valueOf(cell.getStringCellValue()).contains("NGP")) { mtnIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains("Location")) { passwordIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains("NPANXX")) { ssnIndex = cell.getColumnIndex(); } else if (String.valueOf(cell.getStringCellValue()).contains(Status.STATUS.toString())) { statusCol = cell.getColumnIndex(); } if (mtnIndex != -1 && passwordIndex != -1 && ssnIndex != -1 && statusCol != -1) { break; } } if (statusCol == -1) { statusCol = (workSheet.getRow(0).getPhysicalNumberOfCells()); Cell cell = workSheet.getRow(0).createCell(statusCol); cell.setCellValue(Status.STATUS.toString()); } for (int i = 1; i < workSheet.getPhysicalNumberOfRows(); i++) { Cell cell = null; if (workSheet.getRow(i).getCell(statusCol) == null || (workSheet.getRow(i).getCell(statusCol).getCellType() == Cell.CELL_TYPE_BLANK)) { cell = workSheet.getRow(i).createCell(statusCol); cell.setCellValue(Status.UNUSED.toString()); } cell = workSheet.getRow(i).getCell(statusCol); if (cell.getStringCellValue().toString().equals(Status.UNUSED.toString())) { npaNXX.NGP = String.valueOf(workSheet.getRow(i).getCell(mtnIndex).getNumericCellValue()); npaNXX.Location = workSheet.getRow(i).getCell(passwordIndex).getStringCellValue(); npaNXX.NPANXX = String.valueOf(workSheet.getRow(i).getCell(ssnIndex).getNumericCellValue()); cell.setCellValue(Status.INUSE.toString()); break; } } } catch (Exception ex) { ex.printStackTrace(); } finally { WriteAndCloseFile(filePath, fileInput, workBook); } if (npaNXX == null) Log.error("FAILED To get account details; one among MTN/Password/SSN is blank"); return npaNXX; }
From source file:com.ctb.importdata.ImportSFDataProcessor.java
public static ArrayList<SalesForceLicenseData> readDataFromXLSXFile(String fileName) { File sfDataFile = new File(fileName); FileInputStream fileInputStream = null; ArrayList<SalesForceLicenseData> sfLicenseDataList = null; //read the file in to stream if (sfDataFile.exists()) { //System.out.println("Reading data from .xlsx file started."); logger.info("Reading data from .xlsx file : Started :: Timestamp >> " + new Date(System.currentTimeMillis())); try {//from w w w . ja v a 2 s. co m fileInputStream = new FileInputStream(sfDataFile); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); sfLicenseDataList = new ArrayList<SalesForceLicenseData>(); SalesForceLicenseData sfld = null; if (sheet != null) { int totalRows = sheet.getPhysicalNumberOfRows(); //System.out.println("Total no. of physical rows in file = "+ totalRows); logger.info("Total no. of physical rows in file = " + totalRows); Row headerRow = sheet.getRow(0); Cell headerCell; Cell dataCell; if (headerRow == null) { //System.out.println("No file header content found.") ; logger.info("No file header content found."); } else { int totalHeaderColumns = headerRow.getPhysicalNumberOfCells(); //System.out.println("Total no. of header cells = "+ totalHeaderColumns); //logger.info("Total no. of header cells = "+ totalHeaderColumns); for (int rowCtr = 1; rowCtr < totalRows; rowCtr++) { //System.out.println("Row No. >> "+rowCtr); Row dataRow = sheet.getRow(rowCtr); if (dataRow != null) { int totalRowColumns = dataRow.getPhysicalNumberOfCells(); //System.out.println("Total no. of current data row cells = "+ totalRowColumns); //logger.info("Total no. of current data row cells = "+ totalRowColumns); logger.info( "Row No. [" + rowCtr + "] :: Header Column Count = [" + totalHeaderColumns + "] :: Current Data Row Column Count = [" + totalRowColumns + "]"); //Discard dummy rows in spreadsheet if the count of current data row columns not equal to header columns if (totalHeaderColumns == totalRowColumns) { boolean isCustomerIdBlank = dataRow.getCell(0) .getCellType() == Cell.CELL_TYPE_BLANK ? true : false; boolean isOrgNodeIdBlank = dataRow.getCell(5) .getCellType() == Cell.CELL_TYPE_BLANK ? true : false; //System.out.println("isCustomerIdBlank >> "+isCustomerIdBlank+" :: isOrgNodeIdBlank >> "+isOrgNodeIdBlank); logger.info("Row No. [" + rowCtr + "] :: isCustomerIdBlank >> " + isCustomerIdBlank + " :: isOrgNodeIdBlank >> " + isOrgNodeIdBlank); //Condition to skip row for SF data object population if customer id or orgnode id is blank if (!isCustomerIdBlank && !isOrgNodeIdBlank) { sfld = new SalesForceLicenseData(); // For each row, loop through each column for (int colCtr = 0; colCtr < totalHeaderColumns; colCtr++) { //System.out.println("Column No. >> "+colCtr); headerCell = headerRow.getCell(colCtr); dataCell = dataRow.getCell(colCtr); if (dataCell != null) { //System.out.println("dataCell.getCellType() >> "+dataCell.getCellType()); switch (dataCell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: //Do nothing System.out.println(dataCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: //System.out.println(dataCell.getNumericCellValue()); populateSFDataNumericColValue(sfld, dataCell, headerCell); break; case Cell.CELL_TYPE_STRING: //System.out.println(dataCell.getStringCellValue()); populateSFDataStrColValue(sfld, dataCell, headerCell); break; case Cell.CELL_TYPE_BLANK: //System.out.println(" "); populateSFDataBlankColValue(sfld, dataCell, headerCell); break; default: System.out.println(dataCell); break; } } } sfLicenseDataList.add(sfld); } } } } } } } catch (FileNotFoundException e) { logger.error("FileNotFoundException : occurred while procesing :: Filename >> [" + fileName + "]"); e.printStackTrace(); // unexpected } catch (IOException e) { logger.error("IOException : occurred while procesing :: Filename >> [" + fileName + "]"); e.printStackTrace(); } finally { try { if (fileInputStream != null) fileInputStream.close(); } catch (IOException e) { logger.error("IOException : occurred while closing file input stream."); e.printStackTrace(); } } //System.out.println("Reading data from .xlsx file completed."); logger.info("Reading data from .xlsx file : Completed :: Timestamp >> " + new Date(System.currentTimeMillis())); } else { //System.out.println("File does not exists"); logger.error("File does not exists :: Filename >> [" + fileName + "]"); } return sfLicenseDataList; }