这是我的代码,用来显示excel数据文件中的所有数据。
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();
}
}
}
我这里有两个问题
NullPointerException
在它显示所有数据后JTable
编辑:这是在Jtable上显示excel文件数据的代码,但它给了我一个ArrayOutofBounds异常。
这是在Jtable上显示excel文件数据的代码,但它给我一个ArrayOutofBounds异常。
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();
}
}
}
所有你的 ArrayIndexOutOfBoundsException
我想从这个小部分来。
for (i = 0; i <= 5; i++) {
for (j = 0; j <= 2; j++) {
// ...
}
}
你看到错误了吗?
我们再仔细看看。
i <= 5; j <= 2;
数组有N个项目,但它们的索引从... ... 0
到 N - 1
想象一下,你有5个项目。
Index N
0 1
1 2
2 3
3 4
4 5
5 ???
你告诉你的程序要从以下项目开始迭代 0
到 5
,而在索引5处你什么都没有,你检查的东西是出界的!
如何解决这个问题呢?移除 =
比较的部分
i < 5; j < 2;
或者更好的是,使用一个 Iterator
为你的Excel文件,这样一来,不管你有1个或1000个或100万个条目,你都不用为每一个条目修改你的程序,你也可以增加更多的列,你的程序也不会崩溃。
至于你的 JTable
我下面的回答是基于 本回答 其中,您的数据来自于一个 ArrayList
的数据,但你开始你的 DefaultTableModel
与 0
的条目,并在之后添加。
在这里,我教你如何。
ArrayList
后要显示的是JTable
有假数据JTable
与从步骤2中得到的Excel文件中的数据。所有这些数据都被嵌入到一个合适的 最低限度的、可复制的例子(MRE) 而这也是我们希望你在以后的问题中能做到的。这道题是个例外,因为你真的不知道如何让你的程序运行,但在你以后的问题中,我们会要求你创建这样的东西,让我们复制-粘贴,并且能够在不做任何改动(最好是)的情况下运行你的程序。
在这种情况下,你只要修改一下就可以运行我的程序。文件路径
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);
}
}
当你运行上面的程序时,你会得到这样的结果。
这是控制台的输出(excel文件包含相同的信息)。
NAME PROFESSION SALARY
FOO FOO_PROF 12345.0
BAR BAR_PROF 13579.0
WAKANDA WAKANDA_PROF 99999.0