/**
- 观看记录类
- @author mrchai
*/
public class Record {
/** 序号 /
private int num;
/* 学生姓名 /
private String stuName;
/* 观看时长 */
private String viewTime;
public Record() {
// TODO Auto-generated constructor stub
}
//setter/getter
}
/**
* 读取Excel文件(xls,非xlsx)
*
* @param excelFile
* @throws IOException
* @throws BiffException
*/
public static List readExcel(File excelFile) throws BiffException, IOException {
// 声明一个集合用于存储读取到的每一行数据
List<Record> list = new ArrayList<>();
// 根据提供的文件获取一个工作簿(Excel表格)
Workbook book = Workbook.getWorkbook(excelFile);
// 获取工作簿中的所有表单
Sheet[] sheets = book.getSheets();
// 获取第一个表单
Sheet s = sheets[0];
//Sheet s = book.getSheet(0); //等同于 book.getSheets()[0]
// 获取数据的总行数
int rows = s.getRows();
// 遍历每一行
for (int i = 1; i < rows; i++) {
// 获取每一行
Cell[] cells = s.getRow(i);
// 声明一个引用变量用于表示读取的一个record对象
Record record = new Record();
// 设置序号
record.setNum(i);
// 设置学生名称
record.setStuName(cells[0].getContents());
// 设置观看时长
record.setViewTime(cells[2].getContents());
// 将读取到的一个对象存入集合
list.add(record);
}
//关闭资源
book.close();
return list;
}
/**写
* 向指定的文件中写入集合数据
*
* @param target 目标文件(生成的文件)
* @param list 数据集
* @throws IOException
* @throws WriteException
* @throws RowsExceededException
*/
public static void writeExcel(File target, List list)
throws IOException, RowsExceededException, WriteException {
// 创建一个工作簿
WritableWorkbook book = Workbook.createWorkbook(target);
// 创建表单(参数1:表单名称;参数2:索引)
WritableSheet sheet = book.createSheet(“sheet1”, 0);
// 创建单元格(设置单元格所在的列,行,文本内容)
Label label1 = new Label(0, 0, "序号");
Label label2 = new Label(1, 0, "姓名");
Label label3 = new Label(2, 0, "观看时长");
// 将单元格加入到表单中
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
for (int i = 0; i < list.size(); i++) {
//获取一条记录
Record record = list.get(i);
//创建单元格并设置位置和内容
label1 = new Label(0, i+1, String.valueOf(record.getNum()));
label2 = new Label(1, i+1, record.getStuName());
label3 = new Label(2, i+1, record.getViewTime());
// 将单元格加入到表单中
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
}
//将数据写入到目标
book.write();
book.close();
}