需要poi.jar包的支持`
@Override
public File exportFile(String fileName,DriverInfo obj) {
//集合列的宽度
final int[] colWidth={2000,2000,5000,5000,5000,5000};
//字段名集合
List<String> fieldList = new ArrayList<>();
fieldList.add("编号");
fieldList.add("姓名");
fieldList.add("联系电话");
fieldList.add("性别");
fieldList.add("年龄");
fieldList.add("创建时间");
//获取数据库里数据
List<DriverInfo> list = dao.findListByPage(obj);
//创建workBook对象
HSSFWorkbook workBook = new HSSFWorkbook();
//在对象中创建一个司机表
HSSFSheet diverSheet = workBook.createSheet("car_diver");
//设置每列的宽度
for(int i=0;i<colWidth.length;i++){
diverSheet.setColumnWidth(i, colWidth[i]);
}
//单元格样式对象
HSSFCellStyle cellStyle = workBook.createCellStyle();
//设置文本居中
//cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//创建第0行做为表头
HSSFRow row=diverSheet.createRow(0);
HSSFCell cell =null;
for(int i=0;i<colWidth.length;i++){
cell=row.createCell(i);
//获取动态字段名
cell.setCellValue(fieldList.get(i));
cell.setCellStyle(cellStyle);
}
int j =0;
for (int i = 1; i < list.size()+1; i++) {
//循环将查询出来的数据封装到表格的一行中
row=diverSheet.createRow(i);
do{
j=0;
cell=row.createCell(j);
cell.setCellValue(list.get(i-1).getId());
j++;
cell=row.createCell(j);
cell.setCellValue(list.get(i-1).getName());
j++;
cell=row.createCell(j);
cell.setCellValue(list.get(i-1).getTelephone());
j++;
cell=row.createCell(j);
if(list.get(i-1).getSex()==1){
cell.setCellValue("男");
}else{
cell.setCellValue("女");
}
j++;
cell=row.createCell(j);
cell.setCellValue(list.get(i-1).getAge());
j++;
cell=row.createCell(j);
cell.setCellValue(list.get(i-1).getCreateTime());
}while(j<5);
}
FileOutputStream fos;
try {
File file = new File(fileName);
fos = new FileOutputStream(fileName);
workBook.write(fos);
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}