Java使用jxl读取excel表格后使用数组统计人数
假设你已经成功使用 JXL 库读取了 Excel 表格,可以使用数组来统计人数。参考以下示例:
import jxl.*;
import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) throws IOException, BiffException {
// 读取 Excel 表格
Workbook workbook = Workbook.getWorkbook(new File("data.xls"));
// 获取第一个工作表
Sheet sheet = workbook.getSheet(0);
// 获取行数和列数
int rows = sheet.getRows();
int cols = sheet.getColumns();
// 统计人数
int count = 0;
// 遍历每一行
for (int i = 1; i < rows; i++) {
// 获取当前行的单元格数组
Cell[] cells = sheet.getRow(i);
// 如果第一列的单元格内容不为空,则该行为一条记录
if (!cells[0].getContents().isEmpty()) {
count++;
}
}
System.out.println("人数:" + count);
// 关闭工作表和工作簿
sheet.close();
workbook.close();
}
}
首先,使用jxl读取excel表格需要下载jxl的jar包,并将其导入项目中,然后使用以下代码读取excel表格中的数据:
File file = new File("example.xls"); // excel文件
Workbook workbook = Workbook.getWorkbook(file); // 获取workbook
Sheet sheet = workbook.getSheet(0); // 获取第一个sheet
int rows = sheet.getRows(); // 获取行数
int cols = sheet.getColumns(); // 获取列数
String[][] data = new String[rows][cols]; // 存储数据的二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
Cell cell = sheet.getCell(j, i); // 获取单元格
data[i][j] = cell.getContents(); // 获取单元格内容并存入数组
}
}
接下来,我们需要使用数组统计人数。假设excel表格中第一列是姓名,第二列是年龄,则可以使用以下代码统计不同年龄段的人数:
int[] count = new int[5]; // 存储不同年龄段人数的数组
for (int i = 1; i < rows; i++) { // 从第二行开始遍历
int age = Integer.parseInt(data[i][1]); // 获取年龄
if (age < 20) {
count[0]++;
} else if (age < 30) {
count[1]++;
} else if (age < 40) {
count[2]++;
} else if (age < 50) {
count[3]++;
} else {
count[4]++;
}
}
// 输出不同年龄段的人数
System.out.println("20岁以下人数:" + count[0]);
System.out.println("20-29岁人数:" + count[1]);
System.out.println("30-39岁人数:" + count[2]);
System.out.println("40-49岁人数:" + count[3]);
System.out.println("50岁及以上人数:" + count[4]);
这样就可以使用jxl读取excel表格,并使用数组统计人数了。