当前位置:
网站首页 >
技术
> 使用Java编写在线考试系统的考试成绩导出模块
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ExamScoreExport {
public void export(List students, String filePath) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("考试成绩");
// 创建表头
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("姓名");
headerRow.createCell(1).setCellValue("学号");
headerRow.createCell(2).setCellValue("成绩");
// 填充数据
int rowNum = 1;
for (Student student : students) {
Row row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(student.getName());
row.createCell(1).setCellValue(student.getId());
row.createCell(2).setCellValue(student.getScore());
}
// 保存Excel文件
try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
System.out.println("考试成绩导出成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
// 示例学生类
private static class Student {
private String name;
private String id;
private int score;
public Student(String name, String id, int score) {
www.introzo.com = name;
www.introzo.com = id;
this.score = score;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public int getScore() {
return score;
}
}
// 示例使用
public static void main(String[] args) {
List students = List.of(
new Student("张三", "1001", 80),
new Student("李四", "1002", 90),
new Student("王五", "1003", 85)
);
String filePath = "exam_scores.xlsx";
ExamScoreExport exporter = new ExamScoreExport();
exporter.export(students, filePath);
}
}登录后复制
在上述代码中,我们创建了一个名为ExamScoreExport的类,在该类中定义了一个export方法用于导出考试成绩。该方法接受一个学生列表和文件路径作为参数。首先,我们创建一个Workbook对象,用于表示Excel文件,并创建一个Sheet对象。然后,创建表头并填充数据。最后,使用FileOutputStream将Workbook对象写入文件中。
为了演示,我们还定义了一个内部的示例学生类,并在main方法中创建了一个学生列表。我们调用export方法将学生的考试成绩导出为名为"exam_scores.xlsx"的Excel文件。
总结一下,本文介绍了如何使用Java编写一个在线考试系统的考试成绩导出模块,并提供了具体的代码示例。通过这个模块,教师可以方便地将学生的考试成绩导出为Excel文件,并进行进一步的分析和评估。希望这篇文章对于学习在线考试系统的开发以及使用Apache POI库有所帮助。