导出数据库数据到Excel表

后台需要将用户信息数据导入到Excel表中提供给相关人员:

首先查询数据就不多说了;

导入Excel表直接亮代码(采用的是jxl的jar包提供的方法):

public static File ImportToExcel(List<String> data,String title) {
log.info("数据导入条数:{},标题:{}",data.size(),title);
WritableWorkbook workbook = null;
WritableSheet sheet = null;
Label label = null;
if (!title.equals("cellphone") && !title.equals("email")) {
log.info("数据标题不正确");
return null;
}
// 创建Excel表
File file = null;
try {
file = new File(System.getProperty("java.io.tmpdir")+title+".xlsx");
workbook = Workbook.createWorkbook(file);
//workbook = Workbook.createWorkbook(os);

// 创建Excel表中的sheet
sheet = workbook.createSheet("First Sheet", 0);

// 向Excel中添加数据
int row = 0;
// 添加标题
label = new Label(0, row, title.equals("cellphone") ? "手机信息表" : "邮箱信息表");
// log.debug("标题:"+i+"---"+row +"---"+ colName);
sheet.addCell(label);
log.debug("写入标题成功");
for (int i = 0; i < data.size(); i++) {
label = new Label(0, i+1, data.get(i));
sheet.addCell(label);
}
log.debug("写入内容成功");

// 关闭文件
workbook.write();
workbook.close();
log.info("数据成功写入Excel");
} catch (RowsExceededException e) {
log.debug(e.getMessage());
} catch (WriteException e) {
log.debug(e.getMessage());
} catch (IOException e) {
log.debug(e.getMessage());
} finally {
try {
workbook.close();
} catch (Exception e) {
}
}
return file;
}

思路:先创建一个tomcat临时文件的Excel表:new File(System.getProperty("java.io.tmpdir")+title+".xlsx")

再用jxl提供的接口方法将数据写入表中;最后将表下载到本地:

File file = ExcelUtil.ImportToExcel(data, name);
response.addHeader("Content-Type", "application/vnd.ms-excel");
response.addHeader("Content-Disposition","attachment; filename="+file.getName());
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(file);
os = response.getOutputStream();
IOUtils.copy(is, os);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}

 

posted on 2017-07-03 14:15  断剑重铸之时  阅读(146)  评论(0编辑  收藏  举报