初学Poi让我很头疼,版本问题影响很大,所以说百度的时候要注意版本一致,有不理解的地方欢迎评论。
首先创建一个 HSSFWorkbook 对象,该对象用于创建样式,excel文件
//创建Excel操作对象
HSSFWorkbook wb = new HSSFWorkbook();
设置sheet页 初始化行
//设置Sheet页
HSSFSheet sheet = wb.createSheet("异常设备列表");
//初始化行对象
HSSFRow row = null;
获取第一行对象
//获取第一行对象
row = sheet.createRow(0)
给第一行的第一个单元格填充数据
//开始行
row = sheet.createRow(0);
//createCell(0) 获取坐标为0的单元格 setCellValue("value") 填充单元格的值
row.createCell(0).setCellValue("序号");//为第一个单元格设值
row.createCell(1).setCellValue("设备编号");//为第二个单元格设值
row.createCell(2).setCellValue("企业名称");//为第三个单元格设值
row.createCell(3).setCellValue("站点名称");//为第四个单元格设值
row.createCell(4).setCellValue("站点地址");//为第四个单元格设值
row.createCell(5).setCellValue("街道名称");//为第四个单元格设值
row.createCell(6).setCellValue("综合体");//为第四个单元格设值
row.createCell(7).setCellValue("厂家");//为第四个单元格设值
row.createCell(8).setCellValue("数据更新时间");//为第四个单元格设值
拿到我要填充的数据集
//我的测试数据
List<Map> list =homeService.exportDevicesOrder(param);
遍历数据集依次往单元格填充数据
for (int i = 0; i < list.size(); i++) {
//开始行
row = sheet.createRow(i + 1);
//结果集
Map po = list.get(i);
//第一列的序号
row.createCell(0).setCellValue((i+1)+"");
//获取结果集的字段值
row.createCell(1).setCellValue(po.get("device_id") ==null?"":po.get("device_id").toString());
row.createCell(2).setCellValue(po.get("enterprise_name") ==null?"":po.get("enterprise_name").toString());
row.createCell(3).setCellValue(po.get("point_name") ==null?"":po.get("point_name").toString());
row.createCell(4).setCellValue(po.get("point_address") ==null?"":po.get("point_address").toString());
row.createCell(5).setCellValue(po.get("street_name") ==null?"":po.get("street_name").toString());
row.createCell(6).setCellValue(po.get("synthesis_name") ==null?"":po.get("synthesis_name").toString());
row.createCell(7).setCellValue(po.get("vendor") ==null?"":po.get("vendor").toString());
row.createCell(8).setCellValue(po.get("data_collect_time") ==null?"无":po.get("data_collect_time").toString());
}
然后是如何设置样式,其它样式可以自己百度。
// 生成一个样式
HSSFCellStyle style = wb.createCellStyle();
// 生成一个字体
HSSFFont font = wb.createFont();
//颜色
font.setColor(IndexedColors.BLACK.getIndex());
//大小
font.setFontHeightInPoints((short) 16);
//加粗
font.setBold(true);
//格式
font.setFontName("宋体");
//使用字体样式
style.setFont(font);
//字体居中
style.setAlignment(HorizontalAlignment.CENTER);
最后
// 我写的通用方法
wb = expordExcel.getExpordExcel(map1);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
OutputStream os = response.getOutputStream();
response.setHeader("Content-disposition", "attachment;filename=deviceList.xls");//默认Excel名称
wb.write(os);
os.flush();
os.close();
最后加上一个自己敲的通用方法 谢谢
https://download.csdn.net/download/Hkemp/19874110?spm=1001.2014.3001.5501