简单实现将数据导出成excel形式,使用jxl.jar包,直接下载jexcelapi_2_6_12.tar.gz压缩就有。
注意:导出excel文件时,表格名后缀最好使用.xls,最新的.xlsx测试后出问题,表格中没有内容,具体原因不清楚。
第一步:User实体类
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
第二步:生成表格
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class Test {
//模拟数据得到list
public static List getUser(){
List list = new ArrayList();
for(int i =0;i<10;i++){
User user = new User();
user.setName("name"+i);
user.setPassword("password"+i);
list.add(user);
}
return list;
}
public static void main(String[] args) throws Exception{
List list = getUser();
WritableWorkbook book = Workbook.createWorkbook(new File("C:\\Users\\admin/Desktop/zuche.xls"));
//生成"第一页"工作表
WritableSheet sheet = book.createSheet("第一页", 0);
SheetSettings ss = sheet.getSettings();
//设置字体
WritableFont f1 = new WritableFont(
WritableFont.createFont("微软雅黑"),10,WritableFont.BOLD);
WritableFont f2 = new WritableFont(
WritableFont.createFont("微软雅黑"),9,WritableFont.NO_BOLD);
WritableCellFormat wcf = new WritableCellFormat(f1);
WritableCellFormat wcf2 = new WritableCellFormat(f2);
//设置居中
wcf.setAlignment(Alignment.CENTRE);//平行居中
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中
wcf2.setAlignment(Alignment.CENTRE);
wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);
//在Label对象的构造中(a,b,c,d)
//指名单元格位置是第a列第b行,单元格元格内容c,单元格格式d
Label titleLable = new Label(1, 0, "用户注册表格",wcf);
sheet.mergeCells(1,0,2,0);//合并单元格
//将定义的单元格添加到工作表中
sheet.addCell(titleLable);
//设置第一行高度
sheet.setRowView(1, 500);
int[] headerArrHight = {13,13};
String headerArr[] = {"用户名","密码"};
for(int i=0;i
sheet.addCell(new Label(i, 1, headerArr[i],wcf));
sheet.setColumnView(i, headerArrHight[i]);
}
//DecimalFormat df = new DecimalFormat("#.00");
int count = 2;
for(int i=0;i
sheet.addCell(new Label(0,count,list.get(i).getName(),wcf2));
sheet.addCell(new Label(1,count,list.get(i).getPassword(),wcf2));
count++;
}
book.write();
book.close();
}
}