List of usage examples for org.apache.poi.xssf.usermodel XSSFSheet getRow
@Override public XSSFRow getRow(int rownum)
From source file:eventHandlers.CompareDrotVSRoster.java
public void colorXLSXFile(String leaveXlsxRoster) throws FileNotFoundException, IOException { File xlsxFile = new File(leaveXlsxRoster); try {/* w w w . ja v a 2s . c om*/ FileInputStream fis = new FileInputStream(xlsxFile); XSSFWorkbook myWorkBook = new XSSFWorkbook(fis); //Return first sheet from the XLSX workbook XSSFSheet mySheet = myWorkBook.getSheetAt(0); //Get iterator to all the rows in current sheet Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file if (rowIterator.hasNext()) { Row headerRow = rowIterator.next(); //skip the header row Iterator<Cell> it = headerRow.cellIterator(); int numCell = 0; // List<String> keyList = new ArrayList<>(); //keep track info of each column while (it.hasNext()) { //keyList.add(it.next().getStringCellValue()); it.next(); numCell++; } if (numCell == GlobalVar.SIGNED_LEAVE_TITLES.length) { // correct xlsx file int rowNum = 1; while (rowIterator.hasNext()) { Row row = rowIterator.next(); //row.getRowStyle(); rowNum++; } for (int i = 1; i < rowNum; i++) { Row row = mySheet.getRow(i); foregroundColorSetUp(row, myWorkBook); //check each row and update foreground color } fis.close(); FileOutputStream output; String targetFile = null; String[] names = leaveXlsxRoster.split("\\."); if (!names[0].equals(leaveXlsxRoster)) { //doesn't contain surfix targetFile = names[0] + "COLORED.xlsx"; } else { targetFile = leaveXlsxRoster + "COLORED.xlsx"; } output = new FileOutputStream(targetFile); myWorkBook.write(output); output.close(); //myWorkBook.write(output); } else { JOptionPane.showMessageDialog(null, "XLSX file doesn't contain correct info!"); } } else { JOptionPane.showMessageDialog(null, "XLSX file is empty!"); System.out.println("The xlsx file is empty!"); } // finds the work book in stance for XLSX file } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "Xlsx file not found!"); } }
From source file:features.UfmCreateXmlFilesForTestData.java
/** * Read the test data in Excel data file and convert data to HashMap and return as output. * @param locOfFile: location of test data file(Excel file with UFM test cases information). * argument is a specifier that is relative to the url argument. */// ww w. j a v a2s .c o m public static HashMap getUfmTestData(String locOfFile) { HashMap<String, String> rowData = new HashMap<String, String>(); try { DataFormatter formatter = new DataFormatter(); FileInputStream file = new FileInputStream(new File(locOfInputUfmExcelFile)); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); int noOfRows = sheet.getLastRowNum(); //System.out.println("no of rows:" + noOfRows); int i = 0; Row rowWithColumnNames = sheet.getRow(2); int noOfColumns = rowWithColumnNames.getPhysicalNumberOfCells(); //System.out.println(noOfColumns); String testCaseName = ""; String columnNamesAndValuesOfOneRow = ""; //Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); // System.out.println(rowIterator for (int m = 0; m < noOfRows; m++) { //System.out.println("Ieration number : " + m); Row rowCurrent = rowIterator.next(); if (m <= 3) { continue; } testCaseName = String.valueOf(rowCurrent.getCell(0)); // System.out.println("test case name " + testCaseName); for (int p = 0; p < 84; p++) { //Igonre the columns without any column name in test case excel file if (formatter.formatCellValue(rowWithColumnNames.getCell(p)) == "") { continue; } columnNamesAndValuesOfOneRow = columnNamesAndValuesOfOneRow + formatter.formatCellValue((rowWithColumnNames.getCell(p))).trim() + ":" + formatter.formatCellValue((rowCurrent.getCell(p))).trim() + ";"; } rowData.put(testCaseName, columnNamesAndValuesOfOneRow); columnNamesAndValuesOfOneRow = ""; } file.close(); return rowData; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:features.UfmCreateXmlFilesForTestData.java
/** * Method to read the Ufm input excel file location and the folder location where need store the xml file *///from www.j a va 2 s .c o m public static void getUfmLocations() { HashMap<String, String> rowData = new HashMap<String, String>(); try { DataFormatter formatter = new DataFormatter(); FileInputStream file = new FileInputStream( new File(ReportLibrary.getPath() + "\\testdata\\Ufm_InputData.xlsx")); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); int noOfRows = sheet.getLastRowNum(); Row rowWithColumnNames = sheet.getRow(1); locOfInputUfmExcelFile = sheet.getRow(1).getCell(1).toString(); locOfFolderInWhichXmlToBeStored = sheet.getRow(1).getCell(2).toString(); } catch (Exception e) { } }
From source file:File.XLSX.ReadXLSX.java
/** * @param args the command line arguments *//*from w w w . ja v a 2 s . c o m*/ public void readXLSXFile(String path, String filename, int Fcol, int Lcol, int Frow, int Lrow) { try { //String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; FileInputStream file = new FileInputStream(new File(path + filename + ".xlsx")); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first and last colomn in file //int Fcols = (int) upper.indexOf(Fcol.toUpperCase()); //int Lcols = (int) upper.indexOf(Lcol.toUpperCase()); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); for (int x = Frow; x < Lrow; x++) { Row rows = sheet.getRow(x); if (rows != null) { String key = null; for (int colIndex = Fcol; colIndex <= Lcol; colIndex++) { Cell cell = rows.getCell(colIndex); if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "\t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "\t"); break; } } } } System.out.println(""); } } catch (Exception e) { e.printStackTrace(); } }
From source file:FileHelper.ExcelHelper.java
public DataSheet ReadTestCaseFileFromSheet(String fileName, String sheetName, MyDataHash myDataHash, String rawData) {//from w w w . j a v a 2 s .co m try { File excel = new File(fileName); FileInputStream fis = new FileInputStream(excel); XSSFWorkbook book = new XSSFWorkbook(fis); XSSFSheet sheet = book.getSheet(sheetName); Iterator<Row> itr = sheet.iterator(); DataSheet dataSheet = new DataSheet(); ArrayList<RowDataFromFile> datas = new ArrayList<RowDataFromFile>(); ArrayList<DataHash> dataHash = new ArrayList<>(); int colmnDataStart = 0, colmnDataStop = 0, numReal = 0; ArrayList<NameDynamic> nameDynamic = new ArrayList<NameDynamic>(); ArrayList<DataInput> listDataInput = new ArrayList<>(); ArrayList<DataInputLevel2> dataInputLevel2 = new ArrayList<>(); while (itr.hasNext()) { RowDataFromFile dataRow = new RowDataFromFile(); JsonObject jObjReq = new JsonObject(); String caller = ""; Row row = itr.next(); Iterator<Cell> cellIterator = row.cellIterator(); Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: { String str = cell.getStringCellValue(); if (str.equals("STT")) { while (cellIterator.hasNext()) { Cell cell1 = cellIterator.next(); switch (cell1.getCellType()) { case Cell.CELL_TYPE_STRING: { // System.out.println(cell1.getStringCellValue()); if (cell1.getStringCellValue().equals("Data Request")) { colmnDataStart = cell1.getColumnIndex(); } if (cell1.getStringCellValue().equals("Threads")) { colmnDataStop = cell1.getColumnIndex() - 1; } if (cell1.getStringCellValue().equals("Result Real")) { // System.out.println("Colmn Reail: " + cell1.getColumnIndex()); numReal = cell1.getColumnIndex(); } break; } case Cell.CELL_TYPE_NUMERIC: { System.out.println(cell1.getNumericCellValue()); break; } } } Row row1 = sheet.getRow(1); Row row2 = sheet.getRow(2); Row row3 = sheet.getRow(3); Row row4 = sheet.getRow(4); Cell cellColmn; Cell cellColmn2; int numColmn = colmnDataStart; while (numColmn <= colmnDataStop) { cellColmn = row1.getCell(numColmn); String temp = GetValueStringFromCell(cellColmn); cellColmn2 = row2.getCell(numColmn); NameDynamic nameDy = CutStrGetNameDynamic(GetValueStringFromCell(cellColmn2)); if (nameDy.getIsDyn().equals("1")) { // Check Data is change when run Thread nameDynamic.add(nameDy); } // Add to list save data api listDataInput.add(new DataInput(temp, nameDy.getName())); DataHash dataHt = myDataHash.CheckNameDataIsHash(sheetName, nameDy.getName()); if (dataHt != null) { dataHt.setNumColumn(numColmn); dataHash.add(dataHt); } if (temp.equals("Object")) { // Exist object group datas name ArrayList<DataInput> listDataIputLevel2 = new ArrayList<>(); cellColmn = row3.getCell(numColmn); cellColmn2 = row4.getCell(numColmn); String tempT = GetValueStringFromCell(cellColmn); if (!tempT.equals("")) { while (!GetValueStringFromCell(cellColmn).equals("")) { nameDy = CutStrGetNameDynamic(GetValueStringFromCell(cellColmn2)); if (nameDy.getIsDyn().equals("1")) { // Check Data is change when run Thread nameDynamic.add(nameDy); } dataHt = myDataHash.CheckNameDataIsHash(sheetName, nameDy.getName()); if (dataHt != null) { dataHt.setNumColumn(numColmn); dataHash.add(dataHt); } listDataIputLevel2.add( new DataInput(GetValueStringFromCell(cellColmn), nameDy.getName())); numColmn++; cellColmn = row3.getCell(numColmn); cellColmn2 = row4.getCell(numColmn); } numColmn--; dataInputLevel2.add(new DataInputLevel2(listDataIputLevel2)); } else { dataInputLevel2.add(new DataInputLevel2(listDataIputLevel2)); } } numColmn++; } Gson gson = new Gson(); System.out.println(gson.toJson(listDataInput)); System.out.println(gson.toJson(dataHash)); } break; } case Cell.CELL_TYPE_NUMERIC: { // System.out.println(cell.getNumericCellValue()); if (cell.getNumericCellValue() > 0) { dataRow.setId(row.getRowNum()); String isSecutiry = "no"; int arrIndex = 0; int arrIndexReq = 0; // Object con int arrIndexRow = 0; while (cellIterator.hasNext()) { Cell cell1 = cellIterator.next(); if ((cell1.getColumnIndex() >= colmnDataStart) && (cell1.getColumnIndex() < colmnDataStop)) { if (listDataInput.get(arrIndex).getType().equals("Object")) { JsonObject jObj = new JsonObject(); int i = 0; int size = dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().size(); while (i < size) { if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("String")) { String value = GetValueStringFromCell(cell1); if (!dataHash.isEmpty()) { for (DataHash dataH : dataHash) { if (dataH.getNumColumn() == cell1.getColumnIndex()) { value = EncryptHelper.EncryptData(value, dataH.getAlgorithm(), dataH.getKey(), dataH.getIv()); } } } jObj.addProperty(dataInputLevel2.get(arrIndexReq) .getListDataIputLevel2().get(i).getName(), value); } else if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("Integer")) { int value = GetValueIntegerFromCell(cell1); jObj.addProperty(dataInputLevel2.get(arrIndexReq) .getListDataIputLevel2().get(i).getName(), value); } else if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("Object")) { String value = GetValueStringFromCell(cell1); Gson gson = new Gson(); JsonObject obj = gson.fromJson(value, JsonObject.class); jObj.add(dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getName(), obj); } i++; if (i < size) { cell1 = cellIterator.next(); } } arrIndexReq++; jObjReq.add(listDataInput.get(arrIndex).getName(), jObj); } else if (listDataInput.get(arrIndex).getType().equals("String")) { String value = GetValueStringFromCell(cell1); if (!dataHash.isEmpty()) { for (DataHash dataH : dataHash) { if (dataH.getNumColumn() == cell1.getColumnIndex()) { value = EncryptHelper.EncryptData(value, dataH.getAlgorithm(), dataH.getKey(), dataH.getIv()); } } } jObjReq.addProperty(listDataInput.get(arrIndex).getName(), value); } else if (listDataInput.get(arrIndex).getType().equals("Integer")) { int value = GetValueIntegerFromCell(cell1); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), value); } arrIndex++; } else if (cell1.getColumnIndex() == colmnDataStop) { isSecutiry = GetValueStringFromCell(cell1); dataRow.setNameAlgorithm(isSecutiry); } else if (cell1.getColumnIndex() > colmnDataStop) { if (arrIndexRow == 0) { dataRow.setThread(GetValueIntegerFromCell(cell1)); } else if (arrIndexRow == 1) { dataRow.setResultExpect(GetValueStringFromCell(cell1)); } arrIndexRow++; } } // System.out.println("data: " + jObj.toString()); // System.out.println("data Req: " + jObjReq.toString()); String[] arrR = rawData.split(","); String rawDataNew = ""; char a = '"'; for (String str : arrR) { if (str.charAt(0) == a) { String value = str.substring(1, str.length() - 1); rawDataNew += value; } else { JsonElement je = jObjReq.get(str); if (je.isJsonObject()) { String value = je.toString(); rawDataNew += value; } else { String value = je.getAsString(); rawDataNew += value; } } } String[] arr = isSecutiry.split("-"); if (arr[0].equals("chksum")) { String chksum = CheckSumInquireCard.createCheckSum(isSecutiry, rawDataNew); // System.out.println("chksum: " + chksum); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), chksum); } else if (arr[0].equals("signature")) { String signature = RSASHA1Signature.getSignature(isSecutiry, rawDataNew); // System.out.println("signature: " + signature); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), signature); } // System.out.println("data Request: " + jObjReq.toString()); dataRow.setData(jObjReq); dataRow.setNumReal(numReal); Gson gson = new Gson(); System.out.println("data row: " + gson.toJson(dataRow)); datas.add(dataRow); } break; } } } dataSheet.setDatas(datas); dataSheet.setNameDynamic(nameDynamic); dataSheet.setListDataInput(listDataInput); dataSheet.setDataInputLevel2(dataInputLevel2); Gson gson = new Gson(); // System.out.println("save data: " + gson.toJson(datas)); fis.close(); return dataSheet; } catch (Throwable t) { System.out.println("Throwsable: " + t.getMessage()); return new DataSheet(); } }
From source file:FileHelper.ExcelHelper.java
private void WriteResultTestCaseForSheet(String fileName, String sheetName, DataTestCaseFull data) { try {//from w w w. j a v a2 s .c om File excel = new File(fileName); FileInputStream fis = new FileInputStream(excel); XSSFWorkbook book = new XSSFWorkbook(fis); XSSFSheet sheet = book.getSheet(sheetName); for (RowDataFromFile dataRow : data.getDatas().getDatas()) { Row row = sheet.getRow(dataRow.getId()); Cell cell = row.getCell(dataRow.getNumReal()); if (cell == null) { cell = row.createCell(dataRow.getNumReal()); } if (dataRow.getResultReal() != null) { cell.setCellValue(dataRow.getResultReal()); } } fis.close(); FileOutputStream fos = new FileOutputStream(new File(fileName)); book.write(fos); fos.close(); } catch (Exception t) { System.out.println("Throwable WriteResultTestCaseForSheet " + t.getMessage()); } }
From source file:FLCSS.floridaautomationtestsuite.ufm.UfmCreateXmlFilesForTestData.java
/** * Read the test data in Excel data file and convert data to HashMap and return as output. * @param locOfFile: location of test data file(Excel file with UFM test cases information). * argument is a specifier that is relative to the url argument. *///from w w w . j a va2 s.co m public static HashMap getUfmTestData(String locOfFile) { HashMap<String, String> rowData = new HashMap<String, String>(); try { DataFormatter formatter = new DataFormatter(); FileInputStream file = new FileInputStream( new File("C:\\Users\\23319\\Downloads\\FLCSS-java(5)\\a1\\src\\QATP_R0.xlsx")); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); int noOfRows = sheet.getLastRowNum(); //System.out.println("no of rows:" + noOfRows); int i = 0; Row rowWithColumnNames = sheet.getRow(2); int noOfColumns = rowWithColumnNames.getPhysicalNumberOfCells(); //System.out.println(noOfColumns); String testCaseName = ""; String columnNamesAndValuesOfOneRow = ""; // HashMap<String,String> headerColumnNames = new HashMap<String,String>(); // //int[][] rowWithData = new int[5][]; // for (i = 0; i < 84; i++) { // // System.out.println("hello"); // headerColumnNames.put(formatter.formatCellValue((rowWithColumnNames.getCell(i))),""); // // System.out.println(headerColumnNames.size()); // } //Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); // System.out.println(rowIterator for (int m = 0; m < noOfRows; m++) { //System.out.println("Ieration number : " + m); Row rowCurrent = rowIterator.next(); if (m <= 3) { continue; } testCaseName = String.valueOf(rowCurrent.getCell(0)); // System.out.println("test case name " + testCaseName); for (int p = 0; p < 84; p++) { //Igonre the columns without any column name in test case excel file if (formatter.formatCellValue(rowWithColumnNames.getCell(p)) == "") { continue; } columnNamesAndValuesOfOneRow = columnNamesAndValuesOfOneRow + formatter.formatCellValue((rowWithColumnNames.getCell(p))).trim() + ":" + formatter.formatCellValue((rowCurrent.getCell(p))).trim() + ";"; } rowData.put(testCaseName, columnNamesAndValuesOfOneRow); columnNamesAndValuesOfOneRow = ""; } file.close(); return rowData; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:foodbankyfs.FbMainFx.java
private List<String[]> saveSpreadsheetData() { // Copy spreadsheet contents into memory try {/*from www. j av a 2 s. co m*/ // Initialize xls reading objects FileInputStream fileInputStream = new FileInputStream(spreadsheet); XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); XSSFSheet worksheet = workbook.getSheet(FbConstants.SHEET_NAME); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); List<String[]> tmpData = new ArrayList(); // Save XSSF objects for rewrite wrksheet = worksheet; wrkbook = workbook; // Iterate through all rows in the sheet for (int rowNum = FbConstants.DATA_ROW_START_INDEX; rowNum < worksheet.getLastRowNum(); rowNum++) { // Initialize array that will store cell contents String values[] = new String[FbConstants.NUMBER_OF_COLUMNS]; XSSFRow row = worksheet.getRow(rowNum); // Iterate through cells in each row and store values to an array for (int cellNum = 0; cellNum < FbConstants.NUMBER_OF_COLUMNS; cellNum++) { XSSFCell cell = row.getCell(cellNum, Row.CREATE_NULL_AS_BLANK); String value = ""; if (cell != null) { if (cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) { evaluator.evaluateInCell(cell); } // If cell type is numeric convert the number value to a string if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { double tmpVal = cell.getNumericCellValue(); value = String.format("%.0f", tmpVal); } if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { value = cell.getStringCellValue().toLowerCase(); } } // If a cell row has an empty ID do not include it in data if (cellNum == 0 && value.equals("")) { break; } // Initialize value to 0 if cell is empty if (value.isEmpty()) { // If value is from email or notes field then put empty instead if (cellNum == FbConstants.EMAIL_FIELD || cellNum == FbConstants.NOTES_FIELD) { value = "empty"; } else { value = "0"; } } // Store value in array values[cellNum] = value; } // Store array of values in list tmpData.add(values); } return tmpData; } catch (IOException e) { System.err.println(e); } return null; }
From source file:FormatConvert.exceloperation.Excel2csv.java
public static void copySheets2CSV(XSSFSheet sheet, String csvfile) { int maxColumnNum = 0; Map<Integer, XSSFCellStyle> styleMap = null; try {/* w w w. jav a2s . co m*/ FileWriter fw = new FileWriter(csvfile); String str = ""; for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { XSSFRow srcRow = sheet.getRow(i); if (srcRow != null) { System.out.println(srcRow.getLastCellNum()); System.out.println(srcRow.getFirstCellNum()); // System.out.println(srcRow.getCell(srcRow.getLastCellNum()).toString()); for (int j = srcRow.getFirstCellNum(); j < srcRow.getLastCellNum(); j++) { if (srcRow.getCell(j) != null && j != srcRow.getLastCellNum() - 1) { srcRow.getCell(j).setCellType(1); str = str + srcRow.getCell(j).getReference() + ","; } else if (srcRow.getCell(j) != null) { srcRow.getCell(j).setCellType(1); 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:fyp.POI.POI.java
public static void main(String[] args) throws Exception { FileInputStream fis = new FileInputStream(new File("FA_AAX.xlsx")); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheetAt(0); FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); CellReference cr = new CellReference("C4"); Row row = sheet.getRow(cr.getRow()); Cell cell = row.getCell(cr.getCol()); CellValue cellValue = evaluator.evaluate(cell); switch (cellValue.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: boolean truefalse = cellValue.getBooleanValue(); System.out.println("Boolean" + truefalse); break;/*from w w w . j a va2 s.com*/ case Cell.CELL_TYPE_NUMERIC: double NumericCheck = cellValue.getNumberValue(); if (NumericCheck % 1 == 0) { int Integer = (int) NumericCheck; System.out.println("Integer" + Integer); } else { double Dbl = NumericCheck; System.out.println("Double" + Dbl); } break; case Cell.CELL_TYPE_STRING: String str = cellValue.getStringValue(); System.out.println("String" + str.substring(3)); break; case Cell.CELL_TYPE_BLANK: System.out.println("Blank"); break; case Cell.CELL_TYPE_ERROR: break; } fis.close(); }