您的位置:首页 > 编程语言 > Java开发

Java web查出的数据导出为Excel的表格

2016-06-24 17:09 381 查看
用到Spring MVC和mybaits以及POI。这些网上都有架包。

在HTML文件中:<input type="button" value="导出" onclick="daoChu()"> 实现一个button的click事件:

function daoChu() {

$.ajax({

url : '../rest/device/excellist?req='

+ JSON.stringify(param) + "&d="

+ new Date().getTime(),

success : function(data) {

var json = JSON.parse(data);

if (json.code == 200) {

alert("导出数据完成");

}

}

});

在Controller中实现上面的方法:

@RequestMapping(value = "/excellist", method = RequestMethod.GET)

@ResponseBody

public Result excellist(HttpServletRequest request) {

DeviceQuery query = constructEntity(request, DeviceQuery.class);

String excelName=query.getExcelName();

return deviceService.getDeviceExcelList(query);

}

在service中实现:

public Result getDeviceExcelList(DeviceQuery query,String excelName) {

List<Device> devices = deviceMapper.selectByConditions(query);//这个是mapper中实现的数据查询语句

ExcelUtil(devices,excelName);//调用下面的方法:

return ResultUtil.getSuccessResult(devices);

}

public void ExcelUtil(List<Device> devices,String excelName) {

String[] excelHeader = { "序号", "芯片名", "客户名", "型号", "序列号", "版本号", "访问时间", "时区", "国家" };

// 第一步,创建一个 webbook,对应一个Excel文件

HSSFWorkbook wb = new HSSFWorkbook();

// 第二步,在 webbook中添加一个sheet,对应Excel文件中的sheet

HSSFSheet sheet = wb.createSheet("Campaign");

// 第三步,在sheet中添加表头第0行,注意老版本 poi对Excel的行数列数有限制short

HSSFRow row = sheet.createRow((int) 0);

// 第四步,创建单元格,并设置值表头 设置表头居中

HSSFCellStyle style = wb.createCellStyle();

style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

//实现表中的数据

for (int i = 0; i < excelHeader.length; i++) {

HSSFCell cell = row.createCell(i);

cell.setCellValue(excelHeader[i]);

cell.setCellStyle(style);

sheet.autoSizeColumn(i);

}

//填充表中的数据

for (int i = 0; i < devices.size(); i++) {

row = sheet.createRow(i + 1);

Device device = devices.get(i);

row.createCell(0).setCellValue(device.getId());

row.createCell(1).setCellValue(device.getProName());

row.createCell(2).setCellValue(device.getCusName());

row.createCell(3).setCellValue(device.getModel());

row.createCell(4).setCellValue(device.getSNo());

row.createCell(5).setCellValue(device.getVerCode());

row.createCell(6).setCellValue(device.getVisitTime());

row.createCell(7).setCellValue(device.getTimeZone());

row.createCell(8).setCellValue(device.getCountry());

}

try {

FileOutputStream fount = new FileOutputStream("E:/"+excelName.toString()+".xls");

wb.write(fount);

fount.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

mapper.xml中的selectByConditions方法

<select id="selectByConditions" resultMap="BaseResultMap"

parameterType="DeviceQuery">

select *

from tb_device

where 1=1

</select>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java Java web spring excel POI