Compare data from table with another table with apache POI in Java - java

I want to compare the data from table 1 with all data from table 2 (Line by line), the problem is, how could i iterate .getRow(1) to compare row by row of table 1?
I mean; we are comparing data from table 1 and row 1 with all lines of table 2. When the process ends I would like to continue with .getRow(2) thanks (Code updated)
DataFormatter formatter = new DataFormatter();
int numRows2 = workbook2.getSheetAt(0).getPhysicalNumberOfRows();
int numRows = workbook.getSheetAt(0).getPhysicalNumberOfRows();
int num = 0;
int num2 = 1;
while(numRows!=0) {
numRows--;
String dato = formatter.formatCellValue(workbook.getSheetAt(0).getRow(num2++).getCell(1));
for (int i = 0; i < numRows2; i++) {
String val = formatter.formatCellValue(workbook2.getSheetAt(0).getRow(num++).getCell(1));
if (dato.contains(val)) {
System.out.println("Works " + val);
}else {
System.out.println("No match");
}
}
}

I'm answering my own question, this code works in case someone needs it.
DataFormatter formatter = new DataFormatter();
int numRows2 = workbook2.getSheetAt(0).getPhysicalNumberOfRows();
int numRows = workbook.getSheetAt(0).getPhysicalNumberOfRows();
// int num = 0;
int num2 = 1;
while (numRows > 0) {
numRows--;
int num = 0;
String dato = formatter.formatCellValue(workbook.getSheetAt(0).getRow(num2++).getCell(1));
for (int i = 0; i < numRows2; i++) {
String val = formatter.formatCellValue(workbook2.getSheetAt(0).getRow(num++).getCell(1));
if (dato.contains(val)) {
System.out.println("Works " + val);
} else {
System.out.println("No match");
}
}
}

Related

Importing a .csv file data into java table showing incomplete information

I'm trying to import a .csv file to display in my Java Table. But it shows incomplete data after reaching a certain point.
When I change the data to previous ones it displays just fine
My csv file looks fine too..
Finally this is how I read the file into the table from a menu item in my interface
File file = new File("C:\\Users\\User\\Desktop\\Emerging Coursework\\12_book_list_csv.csv");
try{
Scanner inputStream = new Scanner(file);
inputStream.nextLine();
while (inputStream.hasNextLine()) {
String data = inputStream.nextLine();
String[] values = data.split(",");
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
int rowCount = browseTable.getRowCount();
System.out.println("rowCount: " + rowCount);
int columnCount = browseTable.getColumnCount();
System.out.println("columnCount: " + columnCount);
int nextRow = 0;
boolean emptyRowFlag = false;
String testValue;
do {
testValue = (String) browseTable.getValueAt(nextRow, 0);
if (testValue != null && testValue.length()!=0) {
System.out.println("testvalue:" + testValue);
System.out.println("testValue.length" + testValue.length());
nextRow++;
} else{
emptyRowFlag = true;
}
} while(nextRow < rowCount && !emptyRowFlag);
for (int i = 0; i < columnCount; i++){
browseTable.setValueAt(values[i], nextRow, i);
}
}
} catch(Exception e){
}

ERRORS while writing in excel - Java poi

I've excel sheet of only two columns. The user add y himself and the third one is for checking if the other two columns are valid to insert in he database or not.
While I'm trying to write in the third column after checking the processing going good for couple of rows but if there are more rows, the results for the third column for each row is not correct...
I think the problem here in the for loop if anyone can help it would be really appreciated. Thanks.
here's my code:- ...
#CheckMethodAuthority("PFV2300&limt_print")
public static void importExcel(Upload upload_data) throws IOException,
NoSuchFieldException, SecurityException, IllegalArgumentException,
IllegalAccessException,
ParseException {
String fileName = upload_data.getFileName();
logger.info("H1:" + fileName);
final int expectedSheetIndex = 0; //
Sheet sheet = ExcelUtil.openWorkSheet(new ByteArrayInputStream(upload_data.asBytes()), fileName, expectedSheetIndex);
SYS4000 account = (SYS4000)renderArgs.get("account");
StringBuffer fileUploadErrorMsg = new StringBuffer();
final int expectedTitleRowNum = 1; //
List<POS20083> pos20083List = readAllCellsOfSheet(sheet, expectedTitleRowNum, account.user_no, fileUploadErrorMsg);
int addItem =0;
int upItem =0;
int failItem =0;
File filePath = new File("D:\\play framework workspace\\Coupon_Platform\\public\\sample\\excel\\PFV2300-sample.xlsx");
InputStream file = new FileInputStream(filePath);
XSSFWorkbook WB = new XSSFWorkbook(file);
sheet = WB.getSheetAt(0);
for (POS20083 POS20083: pos20083List)
{
for (int i=0; i<=pos20083List.size(); i++)
{
Row row = sheet.getRow(i);
Cell cell_store_no= (sheet.getRow(i).getCell(0));
Cell cell_control_qty = (sheet.getRow(i).getCell(1));
Cell cell_error_msg = sheet.getRow(i).getCell(2);
sheet.autoSizeColumn(2);
for (int j=0; j<=sheet.getFirstRowNum(); j++)
{
if (row == null)
{
row = sheet.createRow(i);
continue;
}
if (cell_error_msg == null)
{
cell_error_msg = sheet.getRow(i).createCell(2);
continue;
}
if (row.getRowNum()==0)
{
continue;
}
POS20083 pos20083 = POS20083.find("merchant_no= ? and store_no= ?",POS20083.merchant_no, POS20083.store_no).first();
String sql = insert into pos20083 (pos20081_id, merchant_no, store_no, control_qty, id)select 60, ?1, ?2, ?3, pos20083_seq.nextval from dual;
String sql2 = " Select count(store_no) from twc_store"
+ " Where exists (select store_no"
+ " from pos20083"
+ " where twc_store.store_no = ?4)";
String sql3 = " Select count(store_no) from pos20083"
+ " Where exists (select store_no"
+ " from twc_store"
+ " where pos20083.store_no = ?5)";
EntityManager entityManager = JPA.em();
EntityTransaction transaction = JPA.em().getTransaction();
Query query = entityManager.createNativeQuery(sql);
Query query2 = entityManager.createNativeQuery(sql2);
Query query3 = entityManager.createNativeQuery(sql3);
query2.setParameter(4, POS20083.store_no);
query3.setParameter(5, POS20083.store_no);
if (!transaction.isActive())
{
transaction.begin();
}
int insertCount2 = query2.executeUpdate();
int insertCount3 = query3.executeUpdate();
int storeCounts = ObjectUtil.getInteger(query2.getSingleResult());
int storeCounts_pos20083 = ObjectUtil.getInteger(query3.getSingleResult());
if (storeCounts == 0 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) >0)
{
cell_error_msg.setCellValue("Store Number ID doesn't exists in [twc_store]");
sheet.autoSizeColumn(2);
}
if (storeCounts == 0 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) <=0)
{
cell_error_msg.setCellValue("Store Number ID doesn't exists in [twc_store] and and control Quantity coudn't be less or equal ZERO");
sheet.autoSizeColumn(2);
}
if (storeCounts == 1 && storeCounts_pos20083 ==0 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) > 0)
{
query.setParameter(1, POS20083.merchant_no);
query.setParameter(2, POS20083.store_no);
query.setParameter(3, POS20083.control_qty);
int insertCount = query.executeUpdate();
addItem++;
cell_error_msg.setCellValue(" ");
sheet.autoSizeColumn(2);
}
if (transaction.isActive())
{
transaction.commit();
}
file.close();
if (storeCounts == 1 && storeCounts_pos20083 ==0 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) <=0)
{
cell_error_msg.setCellValue("control Quantity coudnot be less or equal ZERO");
sheet.autoSizeColumn(2);
//failItem++;
//file.close();
}
if (storeCounts == 1 && storeCounts_pos20083 ==1 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) <=0)
{
cell_error_msg.setCellValue("Store Number ID already exists and control Quantity coudn't be less or equal ZERO");
sheet.autoSizeColumn(2);
}
if (storeCounts == 1 && storeCounts_pos20083 ==1 && ObjectUtil.getInteger(cell_control_qty.getNumericCellValue()) > 0)
{
cell_error_msg.setCellValue("Store Number ID already exists");
sheet.autoSizeColumn(2);
}
}
}
failItem++;
}
file.close();
FileOutputStream fileout = new FileOutputStream(filePath);
WB.write(fileout);
fileout.flush();
fileout.close();
I've found out the bug and i fixed it
there are was three loops
1- for (POS20083 POS20083: pos20083List)
2- for (int i=0; i<=pos20083List.size(); i++)
3- for (int j=0; j<=sheet.getFirstRowNum(); j++)
so if we remove the first one which isn't useful here because we are getting the data always from the excel sheet so it will works good ...
also the same for the third one too as well its not very useful here in my task too as well ...
so what i need is only the this loop
for (int i=0; i<=pos20083List.size(); i++)
and we can replace the pos20083list which was return the real number of row with this line
int rows = sheet.getPhisicalNumberofRows() - 1
Thanks so much Layne Bernardo for your efforts

sectioning 2d array from input file java

Can someone help me out? A total of 3 sections, section 1 is the first index, the sub sequential sections are the sum total of every 5 index's there after. Do not know why I keep getting an exception error.
public class Main {
public static void main(String[] args) throws IOException {
double min, max, sum = 0, avg = 0;// DecimalFormat class is used to format the output
DecimalFormat df = new DecimalFormat(".0");// DecimalFormat class is used to format the output
DecimalFormat df1 = new DecimalFormat(".00");
int rows = 0, cols = 0;
String names[] = null;
double scores[][] = null;
double scoressec[][] = null;
BufferedWriter writer = null;
try { //Opening the input file
Scanner sc = new Scanner(new File("Input.txt"));//Reading the no of rows and columns
rows = sc.nextInt();//check
cols = sc.nextInt();
names = new String[rows];
scores = new double[rows][cols - 1];
scoressec = new double[rows][0];
/* Getting the data from the input file
* and populate those values into array
*/
for (int i = 0; i < rows; i++) {
names[i] = sc.next();
for (int j = 0; j < cols - 1; j++) {
scores[i][j] = sc.nextDouble();
if (j == 0) {
scoressec[i][1] = scores[i][1];
} else if (j == 5) {
scoressec[i][2] += scores[i][j] - scores[i][1];
} else {
scoressec[i][3] += scores[i][j] - scoressec[i][2];
}
}
} //closing the input file`

running time error when trying to implent a keyword frequency counter in my parser java

I want to implement my input reading method into my main class, I want use my code to parse. It's been fixed now. thanks.
String x;
int count = -1;=
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
}
private List<String[]> termsDocsArray = new ArrayList<String[]>();
private List<String> allTerms = new ArrayList<String>(); //to hold all terms
private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
/**
To start with your code
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
should be in it's own method like .
private void doSomething(){
//This variable will hold all terms of each document in an array.
String text = "Professor, engineering, data, mining, research";
StringTokenizer str = new StringTokenizer(text);
String word[] = new String[10];
String unique[] = new String[10];
String x;
int count = -1;
while (str.hasMoreTokens()) {
count++;
x = str.nextToken();
word[count] = x;
System.out.println(count + ": " + word[count]);
}
System.out.println("---Frequency---");
// create unique words
for (int i = 0; i < 7; i++) {
if ((!Arrays.asList(unique).contains(word[i]))) {
unique[i] = word[i];
}
}
// measuring frequency
int[] measure = new int[10];
for (int a = 0; a < 7; a++) {
if (Arrays.asList(unique).contains(word[a])) {
measure[a] += 1;
System.out.println(unique[a] + " : " + measure[a]);
}
}
}
Secondly in ur given code u have written like
int count = -1;=
which accounts to this error Syntax error on token "=", { expected.It should be
int count = -1;
And since all your code is simply written in class without any method so it is giving you the error saying { expected.
Please make sure you have copied the code correctly.

Reading contents from a text file and storing them into an array

I have a text document that contains a 5x5 table with these values
5 5
39 95 99 56 41
88 8 1 48 75
3 58 13 54 80
92 72 74 25 86
30 38 3 21 2
I have to add them into an array, and display the lowest value(which is 1) and tell the location of the lowest value(row 1 column 2).
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
for(int row = 0;row<array.length;row++) {int[] column = array[row];
{
for(int columnIndex = 0; columnIndex<column.length; columnIndex++);
}
}
try
{
input = new Scanner(fileIn);
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
}
This code actually stores your input into an array.
public static void main(String[] args) {
Scanner input;
File fileIn = new File("src/array2d/array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
int[][] array = new int[5][5];
try
{
input = new Scanner(fileIn);
String values = input.nextLine();
String[] value = values.split("\\s+");
int index = 0;
for(int row = 0;row < 5;row++)
{ index = row;
for(int col = 0 ; col < 5; col++){
array[row][col] = Integer.parseInt(value[index*5 + col]);
}
}
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
Using answer from #vikasn91, I edited it a bit to correctly assign the values to array, find the lowest number and its location in the array:
try {
input = new Scanner(fileIn);
int lowestCol = 0;
int lowestRow = 0;
int lowest = 0;
for (int row = 0; row < 5; row++) {
String values = input.nextLine();
String[] value = values.split("\\s+");
for (int col = 0; col < 5; col++) {
array[row][col] = Integer.parseInt(value[col]);
if (row == 0 && col == 0) {
lowest = array[row][col];
} else if (array[row][col] < lowest) {
lowestCol = col;
lowestRow = row;
lowest = array[lowestRow][lowestCol];
}
}
}
System.out.println("Lowest number: " + lowest);
System.out.println("Found in row: " + lowestRow + ", col: " + lowestCol);
} catch (FileNotFoundException e) {
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
public static void main(String[] args)
{
Scanner input;
File fileIn = new File("array2dtest1.txt");
System.out.println(fileIn.getAbsolutePath());
try
{
input = new Scanner(fileIn);
int row = input.nextInt();
int column = input.nextInt();
int min = Integer.MAX_VALUE;
int val;
int minR=0,minC=0;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
val = input.nextInt();
if(val<min){
min = val;
minR = i;
minC = j;
}
}
}
System.out.println("Min Value is " + min + "\nat position (" + minR + "," + minC + ")" );
}
catch (FileNotFoundException e)
{
System.out.println(fileIn.getName() + " is not found.");
return;
}
input.close();
}
If you're using the Scanner, you don't need to split or parse integers directly. The default delimiter is space.
Scanner s = new Scanner(new FileReader("src/array2d/array2dtest1.txt"));
int numRows = s.nextInt();
int numCols = s.nextInt();
int[][] array = new int[numRows][numCols];
int least = Integer.MAX_VALUE;
int leastRow = -1;
int leastCol = -1;
for(int r = 0; r < numRows; r++) {
for(int c = 0; c < numCols; c++) {
if((array[r][c] = s.nextInt()) < least) {
leastRow = r;
leastCol = c;
}
}
}

Categories