创建文件
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\aa\\student.xls");
try {
//创建一个excel工作簿文件
WritableWorkbook wwb = Workbook.createWorkbook(file);
//关闭工作簿
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
写入数据
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\aa\\student.xls");
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
Random random =new Random();
try {
WritableWorkbook wwb = Workbook.createWorkbook(file);
WritableSheet ws = wwb.createSheet("学生列表", 0);
//添加表头
ws.addCell(new Label(0, 0, "学生编号"));
ws.addCell(new Label(1, 0, "学生姓名"));
ws.addCell(new Label(2, 0, "学生年龄"));
ws.addCell(new Label(3, 0, "学生性别"));
ws.addCell(new Label(4, 0, "学生帐号"));
ws.addCell(new Label(5, 0, "学生密码"));
ws.addCell(new Label(6, 0, "出生日期"));
ws.addCell(new Label(7, 0, "创建时间"));
//添加主题
for (int row = 1; row < 101; row++) {
ws.addCell(new Label(0, row, "学生编号"+row));
ws.addCell(new Label(1, row, "张"+row));
ws.addCell(new Label(2, row, random.nextInt(50)+""));
ws.addCell(new Label(3, row, random.nextInt(2)==0?"女":"男"));
ws.addCell(new Label(4, row, ""+123*row));
ws.addCell(new Label(5, row, "*****"));
ws.addCell(new Label(6, row, sdf.format(new Date())));
ws.addCell(new Label(7, row, sdf2.format(new Date())));
}
wwb.write();
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
读取数据
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\aa\\student.xls");
try {
Workbook wb = Workbook.getWorkbook(file);
//获取第一个工作表,序号从0开始。也可以根据表名称获取
Sheet sheet = wb.getSheet(0);
//获取单元格
int columns = sheet.getColumns();//表格最大列数
int rows = sheet.getRows();//表格最大行数
Cell[] column = sheet.getColumn(0);//获取某列的所有内容
Arrays.stream(column).collect(Collectors.toList()).forEach(s-> System.out.println(s.getContents()));
for (int i = 0; i<rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sheet.getCell(j, i).getContents()+"\t");//getContents()将数据转换为字符串
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
}
注意:
2007版本以前的excel,java写入数据只能写到第65536行。