我就不连数据库取数据了,直接本地新建一个List,将List的数据直接导入到Excel表中,连数据库是一个道理,连数据库就是先查询所有数据再导入Excel表中。
新建User代码
package com.qm.entity;
public class User {
private Integer id;
private String name;
private String sex;
private Integer age;
public User() {
}
public User(Integer id, String name, String sex, Integer age) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
导出数据库的代码
package com.qm.test;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import com.qm.entity.User;
public class TestExcel {
public static void main(String[] args) {
try {
WritableWorkbook wwb = null;
String fileName = "D://user.xls";
File file=new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
wwb = Workbook.createWorkbook(file);
WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
User u1=new User(1,"全敏","男",18);
User u2=new User(2,"刘鑫","男",14);
User u3=new User(3,"奶龙","女",15);
User u4=new User(4,"刘超","女",11);
List<User> list= new ArrayList<User>();
list.add(u1);
list.add(u2);
list.add(u3);
list.add(u4);
for (User user : list) {
System.out.println(user.getId()+"="+user.getName()+"="+user.getSex()+"="+user.getAge());
}
Label labelId= new Label(0, 0, "编号(id)");
Label labelName= new Label(1, 0, "姓名(name)");
Label labelSex= new Label(2, 0, "性别(sex)");
Label labelAge= new Label(3, 0, "年龄(age)");
ws.addCell(labelId);
ws.addCell(labelName);
ws.addCell(labelSex);
ws.addCell(labelAge);
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 labelAge_i= new Label(3, i+1, list.get(i).getAge()+"");
ws.addCell(labelId_i);
ws.addCell(labelName_i);
ws.addCell(labelSex_i);
ws.addCell(labelAge_i);
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行。看效果