0

here's my code to display all the data from an excel data file:

package util;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import java.io.IOException;

public class read {

    public static void main(String[] args) {
        excelRead();
    }

    public static void excelRead(){

        try {
            int i;
            int j;

            String path = "./data/data.xlsx";
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            XSSFSheet sheet = workbook.getSheet("sheet1");
            for (i = 0; i <=5;i++) {
                for (j = 0; j<=2;j++) {
                    String data = sheet.getRow(i).getCell(j).getStringCellValue();
                    System.out.print(data + "   " );
                    if(j == 2){
                        System.out.println("         ");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e){
            e.printStackTrace();
        }
    }

}

I have two problems here,

  1. it displays a NullPointerException after it displays all data
  2. I don't know how to display the data to a JTable

edit :

this is the code to display the excel file data on the Jtable but it gives me an ArrayOutofBounds exception :

package util;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

public class Jtable extends JPanel {
    JTable table;

    public Jtable() {
        try {


            String path = "./data/data.xlsx";
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            XSSFSheet sheet = workbook.getSheet("sheet1");
            String[] column = {"name", "age", "profession", "gender", "company"};
            String[][] data = {
                    { sheet.getRow(0).getCell(0).getStringCellValue(),
                            sheet.getRow(0).getCell(1).getStringCellValue(),
                            sheet.getRow(0).getCell(2).getStringCellValue()},
                    {sheet.getRow(1).getCell(0).getStringCellValue(),
                            sheet.getRow(1).getCell(1).getStringCellValue(),
                            sheet.getRow(1).getCell(2).getStringCellValue()},
                    {sheet.getRow(2).getCell(0).getStringCellValue(),
                            sheet.getRow(2).getCell(1).getStringCellValue(),
                            sheet.getRow(2).getCell(2).getStringCellValue()},
                    {sheet.getRow(3).getCell(0).getStringCellValue(),
                            sheet.getRow(3).getCell(1).getStringCellValue(),
                            sheet.getRow(3).getCell(2).getStringCellValue()},
                    {sheet.getRow(4).getCell(0).getStringCellValue(),
                            sheet.getRow(4).getCell(1).getStringCellValue(),
                            sheet.getRow(4).getCell(2).getStringCellValue()}
            };
            table = new JTable(data, column);
            table.setPreferredScrollableViewportSize(new Dimension(450, 63));
            table.setFillsViewportHeight(true);
            JScrollPane scrollPane = new JScrollPane(table);
            add(scrollPane);
        }catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
        }
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        Jtable panel = new Jtable();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);


    }

    public static void excelRead() {

        try {
            int i;
            int j;

            String path = "./data/data.xlsx";
            XSSFWorkbook workbook = new XSSFWorkbook(path);
            XSSFSheet sheet = workbook.getSheet("sheet1");
            for (i = 0; i <= 5; i++) {
                for (j = 0; j <= 2; j++) {
                    String data = sheet.getRow(i).getCell(j).getStringCellValue();
                    System.out.print(data + "   ");
                    if (j == 2) {
                        System.out.println("         ");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }
    }
}

  • I cannot help you with the JTable, but I can help you with the null pointer, if you post the full stack trace – Kamil Janowski Jun 12 '20 at 16:01
  • 2
    *if you post the full stack trace* - there is no need to post the stack trace. The OP should be able to read the stack trace to determine the line causing the problem. Then the OP should either be able to fix the problem or tell us exactly the statement and the variable on that statement that is null. – camickr Jun 12 '20 at 16:15
  • 2
    For the `NPE`, read the exception and identify which variable is `null`, for the `JTable` first create a `JTable` with dummy data, then convert the information from Excel to the `TableModel`, as shown [in the tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data), then you have it done. – Frakcool Jun 12 '20 at 16:26
  • See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) – Andrew Thompson Jun 13 '20 at 05:59
  • *"two problems here"* SO is not a problem solving site, it is a Q&A site that works best if each question has a dedicated thread. So form the 2nd problem into a question, show your best effort at implementing it, and post a [mre] if you get stuck. Note that the MRE should use hard coded data. By that stage, the Excel aspect is irrelevant. Note also that a spreadsheet is (or can be) much more complicated than a simple table. Not all Excel files can be adequately represented in a `JTable`. – Andrew Thompson Jun 13 '20 at 06:02
  • @camickr thank you! it fixed the nullPointerException immediately! –  Jun 13 '20 at 11:30
  • @Frakcool thanks for the advice! but I want the program to read the file and display it on a JTable on its own do you have any idea on how to turn the "String data" to an array? other people will upload a new excel file every day and they should be displayed on another Jtable according to the button you press . –  Jun 13 '20 at 12:04
  • 1
    Have you tried making your own `JTable` with your own `TableModel` yet? I posted a link to the tutorial. If you haven't, what are you waiting for? For better help sooner post a proper [mre] with static data that shows that you've already tried the `JTable` part, then if you still don't know how to wire the Excel part with the table part I could help – Frakcool Jun 13 '20 at 14:17
  • @Frackool I tried the Jtable but when I use the line sheet.getRow(i).getCell(j).getStringCellValue(); as the data and replace the I with the row number and J with the cell number for each cell its showing me nothing on the frame and on the console it shows me an ArrayOutofBounds exception even though I catch it –  Jun 14 '20 at 11:12
  • Then you're doing something wrong, and you spelled my nickname wrong so I didn't get notified. Please [edit] your question to show your improved code – Frakcool Jun 14 '20 at 15:57
  • @Frakcool I edited the question , I improvised the code to make it shorter when I enter String Data everything works but when I replace the data with sheet.getRow(0).getCell(0).getStringCellValue() I get an ArrayOutofBounds exception –  Jun 15 '20 at 08:25
  • @AndrewThompson the question looks answerable now, what do you think? – Frakcool Jun 15 '20 at 15:05
  • @Frakcool The OP has yet to follow your advice to hard code data for the table and there are still two problems and 0 questions. If you'd like to enter an answer, let me know and I'll remove the close vote. But otherwise, I'm not inclined to reopen it as it currently appears. – Andrew Thompson Jun 15 '20 at 16:03
  • @AndrewThompson I think OP is really lost, I believe this is his first question, so when that's the case I usually guide them with the example of a [mre], so yes, I'll enter an answer. – Frakcool Jun 15 '20 at 16:18
  • 1
    @Frakcool The question is now open for answers. (Sorry it took so long, I got busy with other matters.) – Andrew Thompson Jun 16 '20 at 04:11
  • 1
    @AndrewThompson No problem, I was also busy with some work stuff, I'll make some time for this tomorrow :) – Frakcool Jun 16 '20 at 04:21
  • @Frakcool I solved the ArrayOutOfBounds exception but now I dont know how to Format the table –  Jun 16 '20 at 11:03
  • @Frakcool Its giving the Array outOfBoundsException again when I change the Array column size from 2 to 13 –  Jun 16 '20 at 12:34

1 Answers1

1

All your ArrayIndexOutOfBoundsException I suppose come from this little part:

for (i = 0; i <= 5; i++) {
    for (j = 0; j <= 2; j++) {
        // ...
    }
}

Do you see the error?

Let's look at it more closely:

i <= 5;               j <= 2;

Arrays have N items, but their indexes go from 0 to N - 1, imagine you have 5 items:

Index    N
  0      1
  1      2
  2      3
  3      4
  4      5
  5      ???

You're telling your program to iterate from 0 to 5, and at index 5 you have nothing, you're checking something that's out of the bounds!

How can you fix this? Removing the = part on your comparison

i < 5;           j < 2;

Or better, use an Iterator for your Excel file, this way, it doesn't matter if you have 1 or 1000 or 1 million entries, you won't have to modify your program for each of those, and you can also add more columns and your program won't break.

As for your JTable, my below answer is based on this answer in which your data comes from an ArrayList of data but you start your DefaultTableModel with 0 entries and add them after.

Here, I'm showing you how to:

  1. Display the data that comes from Excel into your console.
  2. Add the data to ArrayLists to be displayed after
  3. Add a JTable with dummy data
  4. Add a JTable with data from the Excel file that you got from step 2.

And all of it is embedded into a proper Minimal, Reproducible Example (MRE) and this is expected from you on your next questions. This question is an exception as you're really lost in how to make your program to work, but on your future questions we will require you to create something like this for us to Copy-Paste and be able to run your program without little to no (preferably) changes.

In this case you can run my program with a single modification: The file path

import java.awt.BorderLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class JTableFromExcel {
    private JFrame frame;
    private JTable simpleTable;
    private JTable excelTable;
    private JScrollPane scrollForSimpleTable;
    private JScrollPane scrollForExcelTable;

    private String[] columnNames = {"Name", "Profession", "Salary"};
    private String[][] data = {{"Foo", "Foo_Prof", "12345"}, {"Bar", "Bar_Prof", "13579"}};

    private List<String> columnNamesFromExcel;
    private List<List<String>> dataFromExcel;

    //Creates the UI
    private void createAndShowGUI() {
        retrieveDataFromExcel();

        frame = new JFrame(getClass().getSimpleName());

        simpleTable = new JTable(data, columnNames);
        scrollForSimpleTable = new JScrollPane(simpleTable);

        DefaultTableModel tableModel = new DefaultTableModel(columnNamesFromExcel.toArray(), 0);
        for (List<String> row : dataFromExcel) {
            tableModel.addRow(row.toArray(new String[0]));
        }

        excelTable = new JTable(tableModel);
        scrollForExcelTable = new JScrollPane(excelTable);

        frame.add(scrollForSimpleTable, BorderLayout.WEST);
        frame.add(scrollForExcelTable, BorderLayout.EAST);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    //Opens the Excel file and sets up the data and column names
    @SuppressWarnings("resource")
    private void retrieveDataFromExcel() {
        FileInputStream excelFile;

        columnNamesFromExcel = new ArrayList<>();
        dataFromExcel = new ArrayList<>();
        try {
            excelFile = new FileInputStream(new File("PATH/TO/YOUR/FILE.xlsx"));
            Workbook workbook = new XSSFWorkbook(excelFile);
            Sheet datatypeSheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = datatypeSheet.iterator(); //We use an iterator to get all rows

            while (iterator.hasNext()) {
                Row currentRow = iterator.next();
                Iterator<Cell> cellIterator = currentRow.iterator();

                List <String> dataRow = new ArrayList<>();
                while (cellIterator.hasNext()) {
                    Cell currentCell = cellIterator.next();
                    if (currentRow.getRowNum() == 0) { //Row 0 is the header
                        if (currentCell.getCellType() == CellType.STRING) {
                            columnNamesFromExcel.add(currentCell.getStringCellValue());
                        } else if (currentCell.getCellType() == CellType.NUMERIC) {
                            columnNamesFromExcel.add(currentCell.getStringCellValue());
                        }
                    } else {
                        if (currentCell.getCellType() == CellType.STRING) {
                            dataRow.add(currentCell.getStringCellValue());
                        } else if (currentCell.getCellType() == CellType.NUMERIC) {
                            dataRow.add(String.valueOf(currentCell.getNumericCellValue()));
                        }
                    }
                    System.out.print(currentCell + " ");
                }
                if (currentRow.getRowNum() > 0) { //Row 0 is the header, if we add the first row, it will add an empty array because we didn't add anything to it before, so we skip it
                    dataFromExcel.add(dataRow);
                }
                System.out.println();

            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JTableFromExcel()::createAndShowGUI);
    }
}

This is what you get when you run the above program

enter image description here

And this is the output on the console (The excel file contains the same information)

NAME PROFESSION SALARY 
FOO FOO_PROF 12345.0 
BAR BAR_PROF 13579.0 
WAKANDA WAKANDA_PROF 99999.0 
Frakcool
  • 10,915
  • 9
  • 50
  • 89