Java读取excel指定sheet中的各行数据,存入二维数组,包括首行,并打印

时间:2021-05-14 20:11:50

1. 读取

//读取excel指定sheet中的各行数据,存入二维数组,包括首行
public static String[][] getSheetData(XSSFSheet sheet) throws IOException {
String[][] testArray = new String[sheet.getPhysicalNumberOfRows()][];
for(int rowId =0;rowId<sheet.getPhysicalNumberOfRows();rowId++){
XSSFRow row = sheet.getRow(rowId);
List<String> testSetList = new ArrayList<String>();
for(int column=0;column<row.getPhysicalNumberOfCells();column++){
row.getCell(column).setCellType(Cell.CELL_TYPE_STRING);
testSetList.add(row.getCell(column).getStringCellValue());
}
testArray[rowId] = (String[])testSetList.
toArray(new String[testSetList.size()]);
}
return testArray;
}

2. 打印

//打印二维数组
public static void printDoubleArray(String[][] testArray) throws IOException{
for(int i =0; i<testArray.length;i++ )
{
for (int j=0; j<testArray[i].length;j++)
{
print(testArray[i][j]+" ||");
}
println();
} }

3. 调用

public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根 File file = new File("testData\\testData.xlsx");
FileInputStream fis = new FileInputStream(file);
@SuppressWarnings("resource")
XSSFWorkbook wb = new XSSFWorkbook(new BufferedInputStream(fis));
printDoubleArray(getSheetData(wb.getSheetAt(0))); }

4. 效果

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZcAAABQCAIAAABanq/iAAAHyElEQVR4nO2cwZnrKBCEFRcBEY+i0WlD2Ax02suG8K68g2wLEKBGRqga1//NYWaQbboayoDlnpxz//3/5/Oz/POvI4QQPUzuF1xsnc1k5rWySTU/GHIBqiFEp1B0MdzcfMUPhlyAagjRKRRdDDc3XzF6yIudJrtIrx5djQK/IBSWiy12injJts4m9W8puLnZIvZGWTTofEXkY9Ehh1wiOwCSV44+OWM1qgaA/ySjC4XlYi+Oeq2z8XOx2Donw83NYqfJGLP3wBt0YdCLrRrHuCELEPTwFyZnGGPtoE8+yRk6hdLpYol/VD6hpKkH2xhb7CeWz6A7RljVVdyQBdDFnHPHGBd7wcZ+QSihiwU7ui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