利用java写出如何统计excel中的数据
时间: 2024-02-11 13:08:22 浏览: 28
可以使用 Apache POI 库来读取和操作 Excel 文件,使用 Java 进行数据统计分析。是一个简单的示例代码,演示何使用 Apache POI 和 Java 进行数据统计分析:
```java
import java.io.FileInputStream;
import java.io;
import org.apache.poi.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) {
try {
// 读取 Excel 文件
FileInputStream file = new FileInputStream("survey.xlsx");
// 创建工作薄和工作表对象
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
// 遍历行和列,统计数据
int totalRespondents = 0;
int maleRespondents = 0;
int femaleRespondents = 0;
int ageSum = 0;
int ageCount = 0;
int salarySum = 0;
int salaryCount = 0;
for (Row row : sheet) {
// 跳过表头行
if (row.getRowNum() == 0) {
continue;
}
// 统计受访者总数
totalRespondents++;
// 统计男性和女性受访者数量
Cell genderCell = row.getCell(2);
String gender = genderCell.getStringCellValue();
if (gender.equals("Male")) {
maleRespondents++;
} else if (gender.equals("Female")) {
femaleRespondents++;
}
// 统计年龄和薪资的总和和数量
Cell ageCell = row.getCell(3);
int age = (int) ageCell.getNumericCellValue();
ageSum += age;
ageCount++;
Cell salaryCell = row.getCell(4);
int salary = (int) salaryCell.getNumericCellValue();
salarySum += salary;
salaryCount++;
}
// 计算平均年龄和平均薪资
double averageAge = (double) ageSum / ageCount;
double averageSalary = (double) salarySum / salaryCount;
// 输出统计结果
System.out.println("Total respondents: " + totalRespondents);
System.out.println("Male respondents: " + maleRespondents);
System.out.println("Female respondents: " + femaleRespondents);
System.out.println("Average age: " + averageAge);
System.out.println("Average salary: " + averageSalary);
// 关闭文件
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码使用 Apache POI 库来读取 Excel 文件,并遍历行和列,统计数据。在统计过程中,我们使用了一些 Java 的基本数据类型和运算符,比如 int、double、+、/ 等。最后,我们输出了统计结果。请注意,该示例代码仅供参考,实际的数据统计分析需要根据具体的需求进行相应的扩展和修改。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)