Java - Need help getting row # of a specific value - java

i'm having a bit of trouble getting the row number of a specific string. Let's say I have a cell content = "HC" at row 9 and using the method findRow(sheet, "HC"). I should get a return value of 9, but right now the return is 0.
The purpose of the excelSheetFinder function is after the row number is returned from findRow(), I can get the cells from a specific column that I input as the parameters(enCol and frCol).
Any help is appreciated!
public static String[] excelSheetFinder(String value, int enCol, int frCol) throws IOException{
String[] shortNames = new String[2];
File excelFile = new File("excel.xlsx");
FileInputStream inputExcelFile = new FileInputStream(excelFile);
XSSFWorkbook wb = new XSSFWorkbook(inputExcelFile);
XSSFSheet sheet = wb.getSheetAt(0);
int shortNameRow = findRow(sheet, value);
System.out.println(shortNameRow);
Row r = sheet.getRow(shortNameRow);
String enCell = r.getCell(enCol).toString();
String frCell = r.getCell(frCol).toString();
shortNames[0] = enCell;
shortNames[1] = frCell;
return shortNames;
}
private static int findRow(XSSFSheet sheet, String value){
//to find row number so we can search through that specific column
int gotRow = 0;
for (Row row: sheet){
for (Cell cell: row){
final DataFormatter df = new DataFormatter();
final XSSFCell cellVal = (XSSFCell) row.getCell(row.getRowNum());
String valueAsString = df.formatCellValue(cellVal);
if (valueAsString.trim() == value){
gotRow = row.getRowNum();
}
}
}
return gotRow;
}

Replace == by .equals for your string comparison:
if (valueAsString.trim() == value)
== tests for reference equality
.equals() tests for value equality

Related

Apache POI copy one row from Excel file to another new Excel File

I am using JAVA 8 and Apache POI 3.17. I have an Excel file and i want to keep only few lines and delete the others. But my Excel have 40K rows and deleting them one by one is quite long (nearly 30 min :/ )
So i try to change my way of doing it. Now i think it's better to only take rows that i need in the excel source and copy to another new one. But what i have tried so far is not efficient.
I have all my rows and want to keep in a List. But this not working and create me a blank excel :
public void createExcelFileFromLog (Path logRejetFilePath, Path fichierInterdits) throws IOException {
Map<Integer, Integer> mapLigneColonne = getRowAndColumnInError(logRejetFilePath);
Workbook sourceWorkbook = WorkbookFactory.create(new File(fichierInterdits.toAbsolutePath().toString()));
Sheet sourceSheet = sourceWorkbook.getSheetAt(0);
List<Row> listLignes = new ArrayList<Row>();
// get Rows from source Excel
for (Map.Entry<Integer, Integer> entry : mapLigneColonne.entrySet()) {
listLignes.add(sourceSheet.getRow(entry.getKey()-1));
}
// The new Excel
Workbook workbookToWrite = new XSSFWorkbook();
Sheet sheetToWrite = workbookToWrite.createSheet("Interdits en erreur");
// Copy Rows
Integer i = 0;
for (Row row : listLignes) {
copyRow(sheetToWrite, row, i);
i++;
}
FileOutputStream fos = new FileOutputStream(config.getDossierTemporaire() + "Interdits_en_erreur.xlsx");
workbookToWrite.write(fos);
workbookToWrite.close();
sourceWorkbook.close();
}
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
newRow = sourceRow;
}
EDIT : Change the method of copyRow it's better but the date have weird format and blank cells from the original row are gone.
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
Integer i = 0;
for (Cell cell : sourceRow) {
if(cell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(cell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(cell.getStringCellValue());
}
i++;
}
}
EDIT 2 : To keep blank cell
private static void copyRow(Sheet newSheet, Row sourceRow, Integer newRowNum, Integer cellToColor) {
Row newRow = newSheet.createRow(newRowNum);
//Integer i = 0;
int lastColumn = Math.max(sourceRow.getLastCellNum(), 0);
for(int i = 0; i < lastColumn; i++) {
Cell oldCell = sourceRow.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if(oldCell == null) {
newRow.createCell(i).setCellValue("");
} else if (oldCell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(oldCell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(oldCell.getStringCellValue());
}
}
}

Why am I getting a dot(period symbol) that is leading each string/value in my program using Apache POI?

I am using Apache POI for the first time to read and store data from an excel file. here's an example of what is happening when I run the program
There should not be any dots in front of the names.
Also, for some of the states, since the values in the excel file are really large, it is showing:
The data from year 2010 to 2017 for .New York is: [1.9405185E7, 1.9526372E7,
1.9625409E7, 1.9712514E7, 1.977358E7, 1.9819347E7, 1.9836286E7, 1.9849399E7]
Can I use BigDecimal to get around this? If so I'm not really sure how. My code for this program is
public class PopulationEval {
public static void main(String[] args) throws IOException,
InvalidFormatException
{
File excelFile = new
File("C:\\Users\\gg\\Documents\\2017census.xlsx");
FileInputStream fis = new FileInputStream(excelFile);
XSSFWorkbook myWorkbook = new XSSFWorkbook(excelFile);
XSSFSheet mySheet = myWorkbook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
int selectedRow = 1;
HashMap GeographicArea = new HashMap();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
int selectedColumn = 1;
ArrayList yearlyData = new ArrayList();
String geographicName = "";
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch(cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
double num = cell.getNumericCellValue();
if(selectedColumn !=1 && selectedRow >=3)
{
yearlyData.add(num);
}
break;
case Cell.CELL_TYPE_STRING:
String stringValue = cell.getStringCellValue();
//System.out.print(stringValue );
if(selectedRow >= 3 && selectedColumn == 1)
{
geographicName = stringValue;
}
if(selectedColumn != 1 && selectedRow >= 3)
{
yearlyData.add(stringValue);
}
break;
}
selectedColumn++;
}
if(!geographicName.isEmpty())
{
GeographicArea.put(geographicName, yearlyData);
}
//System.out.println();
selectedRow++;
}
fis.close();
Scanner input = new Scanner(System.in);
System.out.println("Which state would you like to view data for from
2010 to 2017? Use proper spelling.");
String user = input.nextLine();
if(GeographicArea.containsKey(user))
{
System.out.println("The data from year 2010 to 2017 for " +
user + " is: " + GeographicArea.get(user));
}
}
}
You can use this utility method whenever you want to round your double:
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(Double.toString(value));
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
And in your program when you're adding the double value into the list, wrap that within this method call and provide the "places" as follows:
yearlyData.add(round(num,5));

String Array from excel column

How can I get a string array from a excel column?
Let's say the column is like this
String0
String1
String2
String3
String4
and I want my array to be like: array[0]="String0", array[1]="String1" etc.
This is the code I am currently using but it always returns "null":
public static String[] excelvalue(String columnWanted, int sheet_no, String path) {
int i = 0;
String[] column_content_array = new String[140];
try {
int instindicator = -1;
FileInputStream file = new FileInputStream(new File(path));
HSSFWorkbook filename = new HSSFWorkbook(file);
HSSFSheet sheet = filename.getSheetAt(sheet_no);
Integer columnNo = null;
Integer rowNo = null;
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = sheet.getRow(0);
for (Cell cell : firstRow) {
if (cell.getStringCellValue().equals(columnWanted)) {
columnNo = cell.getColumnIndex();
rowNo = cell.getRowIndex();
}
}
if (columnNo != null) {
for (Row row : sheet) {
Cell c = row.getCell(columnNo);
String cell_value = "" + c;
cell_value = cell_value.trim();
try {
if ((!cell_value.equals("")) && (!cell_value.equals("null")) && (!cell_value.equals(columnWanted))) {
column_content_array[i] = cell_value;
i++;
}
} catch (Exception e) {
}
}
return column_content_array;
}
} catch (Exception ex) {
return column_content_array;
}
return column_content_array;
}
Instead of storing just last reference of row and column, store all of them in a list like:
List<Integer> columnNos = new ArrayList<>();
List<Integer> rowNos = new ArrayList<>();
And in your for loop, just add rows and columns into list like:
if (cell.getStringCellValue().equals(columnWanted)) {
columnNos.add(cell.getColumnIndex());
rowNo.add(cell.getRowIndex());
}
And then you could iterate over rows and columns and continue with your business logic further.

Changing null to blank while reading excel using java

If I use a excel sheet that has blank values, this code gives an error of "java.lang.NullPointerException". Is there a way to change the null values to blank? Thanks.
public class GradesDB {
public static void main (String[] args) throws Exception {
//initiating workbook
File excel = new File("Users/Database.xlsx"); //file location
FileInputStream fis= new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("Students"); //sheet with null value
int rowNum = ws.getLastRowNum() +1;
int colNum = ws.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum]; //storing row and col
//iteration
for (int i =0; i <rowNum; i++) {
XSSFRow row = ws.getRow(i);
for (int j = 0; j <colNum; j++){
XSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value;
System.out.println(value);
}
}
//System.out.println(data[4][3]);
}
public static String cellToString(XSSFCell cell) {
int type;
Object result = null;
type = cell.getCellType();
switch (type) {
case 0 :
result = cell.getNumericCellValue(); //numeric value
break;
case 1 :
result = cell.getStringCellValue(); //string value
break;
case 2 :
result = cell.getBooleanCellValue();
break;
}
return result.toString();
}
}
I am not sure where the problem is.

Java excel - Comparing two strings

I have to check the strings of two xlsx files if they are equal must return the name, but it always returns null, someone can help me?
try
{
FileInputStream fisCod = new FileInputStream(pathC);
XSSFWorkbook wb = new XSSFWorkbook (fisCod);
XSSFSheet sheet = wb.getSheetAt(0);
int lastRow = sheet.getLastRowNum();
for(int i=0; i<lastRow; i++)
{
Row row = sheet.getRow(i);
Cell cell = row.getCell(jobCod);
String tmp = cell.getRichStringCellValue().getString().toLowerCase();
if (tmp.equals(jobName)) //jobName is a String
{
return tmp;
}
else
{
return null;
}
}
fisCod.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
The first mismatch in the above code will cause null to be returned without checking subsequent row values. More than likely, this is the scenario you are describing.
Check all cell values before resorting to returning null when the attempted match fails.
for (int i = 0; i < lastRow; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(jobCod);
String tmp = cell.getRichStringCellValue().getString().toLowerCase();
if (tmp.equals(jobName)) {
return tmp;
}
}
return null; // now return null

Categories

Resources