Read excel and Assign cell Value by column to an array - java

Using apache.poi, I am trying to read an Excel sheet and using the below code, I am printing all the values inside Excel..
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
// Create a loop to print cell values in a row
for (int j = 0; j < row.getLastCellNum(); j++) {
// Print Excel data in console
String location = (row.getCell(j).getStringCellValue()+ "");
System.out.println(location);
}
When I print the location System.out.println(location);, it prints my all Excel sheet data. I haven't any control over there. I am trying divide the value by the column.
Suppose I have 3 cells and I want to get a value like firstname[],lastname[],age[] so that I can do any operation by the indexing. I am not getting any solution.
Here is my full code
https://codeshare.io/anNwy3

Create a 2D String array. When iterating store the contents into the array
String[][] excelData = new String[numColumns][searcsheet.getLastRowNum()];
//numColumns is the number of columns in the excel sheet.
for (int i = 0; i < rowCount + 1; i++) {
Row row = searcsheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
String data = (row.getCell(j).getStringCellValue()+ "");
excelData[j][i] = data;
}
}
This transpose data when storing it into the array (note: excelData[j][i] and not excelData[i][j]).
With this, you can get all the contents of the first column as excelData[0].

Related

How can I populate this 2d array with values from a char array

So I have a grid that is 6 by 7
char[][] grid = new char[6][7];
And is populated with blank spaces using this loop:
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ' ';
}
}
I also have a char[] array that holds 'A's 'B's and blank spaces. For example ch[0] = B, ch[1] = A, ch[8] = " ".
And I am simply trying to populate each slot of the 2d array 'grid' with the contents of the char array one at a time.
I tried to use the same for loop with some changes to populate the grid but when I run it only populates the top row of my grid and I'm not sure why. I have tried to move the i++, and change the for loop parameters but nothing is working and I need help. This is how I am trying to do it:
int i = 0;
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
grid[row][col] = ch[i];
i++;
}
}
If it helps to know I am getting the contents of ch[] from a .csv file and storing it in a char array. When I run this code as is, it perfectly populates the top row of my grid (first row) but then it does not do anything to the remaining rows.
I don't want to change the data types of anything, I know I can get this too work I just need some help.

printing data columnwise in same workbook - java poi

I am using Java and POI to print some data to excel files. I think I am just missing a small logic to solve this question. I have data stored in array lists in following format:
a = [1,2,3] // arraylist
b = [4,5,6] // arraylist
c = [7,8,9] // arraylist
I want to print this data columnwise to excel file in below given format:
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9
The code that I am using is as below:
public final_out = new FileOutputStream(new File(final_output_path));
public XSSFWorkbook workbook = new XSSFWorkbook();
public XSSFSheet sheet = workbook.createSheet("data_vertical_final");
public Row row;
for (int i=0; i < a.size(); i++) {
String value = a.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(13);
cell.setCellValue(value);
}
for (int i=0; i < b.size(); i++) {
String value = b.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(15);
cell.setCellValue(value);
}
for (int i=0; i < c.size(); i++) {
String value = a.get(i);
row = sheet.createRow(i);
Cell cell = row.createCell(17);
cell.setCellValue(value);
}
workbook.write(final_out);
workbook.close();
final_out.close();
Error I am getting:
There is no error, but everything is getting overwritten in new excel file and the final output looks broken. Do I need to make new workbooks for every loop? or there is something I am missing.
P.S:
The data that is shown below is just an example. Some of my original files that I am using are between 1000 to 2000 values or maybe more.
I want to dynamically create the rows and extract the values from arraylists and store it in rows that I created.
Create only a.size() rows,
not a.size() squared rows.
Don't overwrite them in your code.
I assume that a.size() == b.size() and b.size() == c.size().
public List<Row> rows = new ArrayList<Row>(a.size());
for (int i=0; i < a.size(); i++) {
rows.add(sheet.createRow(i));
}
for (int i=0; i < a.size(); i++) {
String value = a.get(i);
Cell cell = rows.get(i).createCell(13);
cell.setCellValue(value);
}
for (int i=0; i < b.size(); i++) {
String value = b.get(i);
Cell cell = rows.get(i).createCell(15);
cell.setCellValue(value);
}
for (int i=0; i < c.size(); i++) {
String value = a.get(i);
Cell cell = rows.get(i).createCell(17);
cell.setCellValue(value);
}
If you already solve the problem:
It would be even cleaner to place a, b and c into one collection and use only one loop to iterate through them (in place of 3 separate loops).
I assume that a is the longest list.
Check this out:
public List<Row> rows = new ArrayList<>(a.size());
for (int i=0; i < a.size(); i++) {
rows.add(sheet.createRow(i));
}
List<List<String>> alphabet = new ArrayList<>();
alphabet.add(a);
alphabet.add(b);
alphabet.add(c);
for(int i=0; i < alphabet.size(); i++) {
for (int j=0; j < alphabet.get(i).size(); j++) {
String value = alphabet.get(i).get(j);
Cell cell = rows.get(j).createCell(13 + i*2); //<- 13, 15, 17...
cell.setCellValue(value);
}
}

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a JTable. I tried Arrays.toString(myTwoDimensionalArrayVariable) but it won't display the string values.
My goal is to check duplicates for every column per row of a destination JTable when user tries to add row values from a source JTable that's why I want to display the contents of the array.
The values on columns are combination of double, String, and int.
int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];
for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}
System.out.println(Arrays.toString(myRowValues));
if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}
I only get this output:
run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;#35fa3ff2]
[[Ljava.lang.Object;#407c448d, [Ljava.lang.Object;#1e78a60e]
Is there any other alternative than using 2 Dimensional Arrays?
I'd appreciate any help.
Thanks.
IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().
EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:
List<List<Object>> objectList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
objectList.add(j, new ArrayList<>());
for (int i = 0; i < 2; i++) {
if (i==0) objectList.get(j).add("string" + j + i);
if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
}
}
System.out.println("OBJECT LIST: "+objectList);
Output:
OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]
Your code should look like this, then:
List<List<Object>> myRowValues = new ArrayList<>();
for (int j = 0; j < myRowCount; j++) {
myRowValues.add(j, new ArrayList<>());
for (int i = 0; i < myColumnCount; i++) {
myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
}
}
System.out.println(myRowValues);

Java: How to store a 2D array within a 1D array

I trying to store my already found 2D array into a 1D array for faster processing later. However, I keep getting a nullPointerException when I try to fill the 1D array. What happens is a txt file has the number of rows and colums that we read first to get the row and column amount for doing the 2D array. Then each index reads the next data element on the txt file and stores it at that index until all 50 000 integer values are stored. That WORKS fine.
Now I want to take that 2D array and store all the elements into a 1D array for faster processing later when looking for answers without using an array list or put them in order, which is fine,
int [][] data = null;
int[] arrayCount = null;
for (int row = 0; row < numberOfRows; row++)
{
for (int col = 0; col < numberOfCols; col++)
{
data[row][col] = inputFile.nextInt();
}
}
//Doesn't Work gives me excpetion
data[0][0] = arrayCount[0];
I tried this in for loops but no matter what I get a NullPointerException
You haven't initialized the data and arrayCount variables, initialize it as follows :
int[][] data = new int[numberOfRows][numberOfCols];
int[] arrayCount = new int[numberOfRows * numberOfCols];
In your case, to copy from 2D to 1D array you may use something like this :
numberOfRows = data.length;
if (numberOfRows > 0) {
numberOfCols = data[0].length;
} else {
numberOfCols = 0;
}
System.out.println("numberOfRows : "+numberOfRows);
System.out.println("numberOfCols : "+numberOfCols);
for (int row = 0, count = 0; row < numberOfRows; row++) {
for (int col = 0; col < numberOfCols; col++) {
arrayCount[count] = data[row][col];
count++;
}
}

How would you go through each row and each column seperatly in two dimensional array

I am just curious as to how that is done. I am writing a small program to get a better understanding of two dimensional arrays. I want to know how I can go though each row and then each column separately using for loops.
Lets say I have a 2D array that is made out of different letters. I want to go through each row and each column and check if a certain letter is there. Then I want it to print how many occurrences of this letter happened in each row and then each column.
First index is row and second index is column.
Assuming that the something[][] is an something[] of something-rows (that is something[i] gives us a row, not a column - if it'S the way round, just change the examples):
public static void loopExample (String[][] someTwoDimArray) {
// Looping rows
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
System.out.println(someTwoDimArray[row][col]);
}
}
// looping columns
for (var col = 0 ; col < someTwoDimArray[0].length ; col++) {
for (var row = 0 ; row < someTwoDimArray.length ; row++) {
System.out.println(someTwoDimArray[row][col]);
}
}
}
I don't know if the first or second index is considered rows or columns, but this is a pretty standard nested loop for iterating over every element of a 2d array.
for(int column = 0; column < array.length(); ++column) {
for(int row = 0; row < array[column].length(); ++row) {
// do stuff to array[column][row]
}
}
Given your update, let's look for the letter 'N', in a 2d char array called myLetters.
int counter = 0;
for(int i = 0; i < myLetters.length(); ++i) {
for(int j = 0; j < myLetters[i].length(); ++j) {
if('N' == myLetters[i][j]) {
++counter;
}
}
}
System.out.println("N occurs " + counter + " times.");
if you have a 2D array if you want to access each cell you will have to use a nested for loop.
eg:
for(int i = 0; i < length1; i++)
for(int j = 0; j<length2; j++){
// do something
to format column first do array[i][j] = //do something
to format row first do array[j][i] = // do something
}
"I tried using a for loop however i dont have a good understanding of for loops and i was wondering how not just go through array in its entirety but small bits like rows and columns"
A for loop is a java control flow statement. It lets you initialize a variable (i and j) it gives you a condition (i
int i = 0
while (i < length1){
//do something
i++
}
if working with arrays for loops are almost always required.

Categories