请看代码:
File file = new File("c:\\db\\test.xls");
Workbook wb = null;
try {
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
if (fileName.endsWith("xls")) {
wb = new HSSFWorkbook(inputStream);// 解析xls格式
} else if (fileName.endsWith("xlsx")) {
wb = new XSSFWorkbook(inputStream);// 解析xlsx格式
}
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
Vector<String> columuNames = new Vector<String>();
Vector<Vector> tableData = new Vector<Vector>();
int i = 0;
for(i = 0;i < 3;i++){
Sheet sheet = wb.getSheetAt(i);// 第i个工作表
我的xls里面有三张工作表
Row row;
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
row = sheet.getRow(firstRowIndex);
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
int rowNum = lastRowIndex - firstRowIndex + 1;//行数
int columuNum = lastCellIndex - firstCellIndex;//列数
for (int k = 1; k < rowNum; k++) {
Vector<Object> rowData = new Vector<Object>();
rowData.add("");
for (int j = 0; j < columuNum; j++) {
if (sheet.getRow(i).getCell(j) == null) {
rowData.add(" ");
} else {
rowData.add(sheet.getRow(i).getCell(j).toString());
}
}
tableData.add(rowData);
}
}
final TableModel model = new DefaultTableModel(tableData, columuNames) ;
//生成table并将其展示出来,下面的代码我就不写了