实现将数据导入表中需要使用到jxl包 https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl/2.6.12废话就不多说了上代码
先创建实体类
private int id;
private String name;
private String sex;
private int num;
public StuEntity() {
}
public StuEntity(int id, String name, String sex, int num) {
this.id = id;
this.name = name;
this.sex = sex;
this.num = num;
}
@Override
public String toString() {
return "StuEntity [id=" + id + ", name=" + name + ", sex=" + sex
+ ", num=" + num + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
运行代码
//创建Excel文件
File file=new File("e:/excel/sheetbook.xls");//如果创建在文件下。必须存在该文件
ArrayList<StuEntity> list=new ArrayList<StuEntity>();
//张三信息
StuEntity s1=new StuEntity();
s1.setId(1);
s1.setName("张三");
s1.setSex("男");
s1.setNum(1800);
list.add(s1);
//李四信息
StuEntity s2=new StuEntity();
s2.setId(2);
s2.setName("李四");
s2.setSex("男");
s2.setNum(1600);
list.add(s2);
//王五信息
StuEntity s3=new StuEntity();
s3.setId(3);
s3.setName("王五");
s3.setSex("男");
s3.setNum(2000);
list.add(s3);
//莉莉信息
StuEntity s4=new StuEntity();
s4.setId(4);
s4.setName("莉莉");
s4.setSex("女");
s4.setNum(1800);
list.add(s4);
try {
//以fileName为文件名来创建一个Workbook
WritableWorkbook wr= Workbook.createWorkbook(file);
// 创建工作表
WritableSheet ws = wr.createSheet("Test Shee book", 0);
//要插入到的Excel表格的行号,默认从0开始
Label labelId= new Label(0, 0, "编号(id)");//第一个参数c表示横 第二个参数r表示高
Label labelName= new Label(1, 0, "姓名(name)");
Label labelSex= new Label(2, 0, "性别(sex)");
Label labelNum= new Label(3, 0, "薪水(num)");
ws.addCell(labelId);
ws.addCell(labelName);
ws.addCell(labelSex);
ws.addCell(labelNum);
for (int i = 0; i < list.size(); i++) {
Label labelId_i= new Label(0, i+1, list.get(i).getId()+"");
Label labelName_i= new Label(1, i+1, list.get(i).getName());
Label labelSex_i= new Label(2, i+1, list.get(i).getSex());
Label labelNum_i= new Label(3, i+1, list.get(i).getNum()+"");
ws.addCell(labelId_i);
ws.addCell(labelName_i);
ws.addCell(labelSex_i);
ws.addCell(labelNum_i);
}
//写进文档
wr.write();
// 关闭Excel工作簿对象
wr.close();
}catch (Exception e){
e.printStackTrace();
}
效果图如下