我这里有两种导出方法,第一种比较繁琐,个人认为第二种更好
需要导出的数据主表关联两张表,将这些数据转化成我们需要的数据导出
方法1
/**
* 导出xls文件的表头
*/
public static final String[] TestToXls = {
"创建时间", "客户名称", "客户编码",
"还款金额", "付款方式", "状态", "类型", "备注", "借还款说明", "还款到",
"审核时间", "审核人", "审核备注"};
/**
* 导出数据到Excel表
*
* @param recordsForm
*/
public void toExcel(QueryRepaymentRecordsForm recordsForm, HttpServletResponse response) {
//这里为导出文件存放的路径
String filePath = "C:\\monthlyOrder\\refund_record\\";
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
// 给要导出的文件起名
String filePath2 = filePath + "月结还款记录" + "_" + fmt.format(new Date()) + ".xls";
WritableWorkbook wb = null;
try {
File file2 = new File(filePath2);
if (!file2.exists()) {
//不存在,创建
file2.createNewFile();
}
wb = Workbook.createWorkbook(file2);//创建xls表格文件
// 表头显示
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.CENTRE);// 水平居中
wcf.setWrap(true);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf.setFont(new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD));// 表头字体 加粗 11号
wcf.setBackground(jxl.format.Colour.GRAY_25);
// 内容显示
WritableCellFormat wcf2 = new WritableCellFormat();
wcf2.setWrap(true);//设置单元格可以换行
wcf2.setAlignment(Alignment.CENTRE);//水平居中
wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf2.setFont(new WritableFont(WritableFont.TIMES, 10));// 内容字体 10号
//导出的xls的第一页,第二页就是0换成1,“sheet1”,也可以修改为自己想要的显示的内容
WritableSheet ws = wb.createSheet("sheet1", 0);
//WritableSheet ws2 = wb.createSheet("sheet2", 1);//第2个sheet页
//ws.addCell(new Label(0,0, "导出结果"));//代表着表格中第一列的第一行显示查询结果几个字
// 导出时生成表头
for (int i = 0; i < TestToXls.length; i++) {
//i,代表的第几列,0,代表第1行,第三个参数为要显示的内容,第四个参数,为内容格式设置(按照wcf的格式显示)
ws.addCell(new Label(i, 0, TestToXls[i], wcf));//在sheet1中循环加入表头
}
//所有需要导出的数据
List<WpOrderMonthly> monthlyList = findExcelInfo(recordsForm);
int k = 1;//从第二行开始写入数据
for (int i = 0; i < monthlyList.size(); i++) {
long createTime = monthlyList.get(i).getCreateTime();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = new Date(createTime);
ws.addCell(new Label(0, k, sf.format(d), wcf2));//创建时间
WpProfieUserExample userExample = new WpProfieUserExample();
userExample.createCriteria().andIdEqualTo(monthlyList.get(i).getUserId().longValue());
List<WpProfieUser> userList = wpProfieUserMapper.selectByExample(userExample);
String customerName = null;
String userCode = null;
if (userList.size() > 0) {