公司让我个新人做数据导出,哎,不会呀,看了一晚上的视频和文档,终于做出来了。
引入jar包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi  excel 插件-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>

//数据导出
public void ExportData(){

//1.查询数据需要导出的数据
List<AccidentTMeeting> accidentTMeetings = meetingDao.findExportData();
//2.运用poi插件生成Excel表
Workbook wb = new HSSFWorkbook(); //创建一个工作簿
Sheet sheet = wb.createSheet(); //创建一个工作表
//设置单元格样式
sheet.autoSizeColumn((short)4);
sheet.setColumnWidth((short)1,5000);
sheet.setColumnWidth((short)2,10000);
sheet.setColumnWidth((short)3,10000);
sheet.setColumnWidth((short)4,10000);

CellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
CellStyle center = wb.createCellStyle();
Font font = wb.createFont();
center.setAlignment(CellStyle.ALIGN_CENTER);
center.setFont(font);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);

//创建表头
Row row = sheet.createRow(0);
row.setHeight((short)500);
String[] title = {"通知人","通知时间","被通知人","会议地点","备注"};
for (int i=0;i<title.length;i++){
Cell cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(center);
}

//遍历数据
Row row1 = null;
AccidentTMeeting accidentTMeeting = null;
for (int i=0;i<accidentTMeetings.size();i++){
accidentTMeeting = accidentTMeetings.get(i);
row1 = sheet.createRow(i+1);
row1.setHeight((short)400);
Cell cell0 = row1.createCell(0);
Cell cell1 = row1.createCell(1);
Cell cell2 = row1.createCell(2);
Cell cell3 = row1.createCell(3);
Cell cell4 = row1.createCell(4);

cell0.setCellStyle(cs);
cell0.setCellValue(accidentTMeeting.getTzr());
cell1.setCellStyle(cs);
cell1.setCellValue(accidentTMeeting.getTzsj().toString());
cell2.setCellStyle(cs);
cell2.setCellValue(accidentTMeeting.getBtzr());
cell3.setCellStyle(cs);
cell3.setCellValue(accidentTMeeting.getHydd());
cell4.setCellStyle(cs);
cell4.setCellValue(accidentTMeeting.getBz());
}
//3.响应发送Excel文件流到客户端,需要设置响应模式
//文件名需要转码,防止乱码
String fileName = "会议记录台账.xls";
try {
fileName = new String(fileName.getBytes("gb2312"),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpServletResponse response = getResponse();
response.reset();
response.setHeader("Content-disposition", "attachment;filename="+fileName);
response.setContentType("application/vnd.ms-excel");

OutputStream out =null;
try {
out = response.getOutputStream();
wb.write(out);
wb.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (out != null){
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
renderNull();
}
posted on 2017-09-13 16:24  Acorn  阅读(309)  评论(0)    收藏  举报