HSSFWorkbook 导出excel java

public String exportExcelList(){
//创建webbook,对应一个excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在webbook中添加一个sheet,对应excel中的sheet
HSSFSheet sheet = wb.createSheet("检查单");
//在sheet中添加表头,添加一行
HSSFRow row = sheet.createRow(0);
//设置每一列的宽,此处可根据实际情况设置.
sheet.setColumnWidth(1, 20*256);
sheet.setColumnWidth(6, 20*256);
sheet.setColumnWidth(7, 20*256);
sheet.setColumnWidth(8, 20*256);
sheet.setColumnWidth(11, 20*256);
sheet.setColumnWidth(12, 20*256);
sheet.setColumnWidth(13, 20*256);
//设置表格样式
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);//内容向左靠齐
Font font = wb.createFont();//为字体设计样式
font.setFontHeightInPoints((short)12); //字体大小
font.setFontName("宋体");
style.setFont(font);//将字体加入到表格样式中
//设置列名称(第一列)
HSSFCell cell = row.createCell(0);
cell.setCellValue("id");//列名称
cell.setCellStyle(style);//列样式
//第二列
cell = row.createCell(1);
cell.setCellValue("syncDate");
cell.setCellStyle(style);
.........
//查出你要的数据
List laboratoryList = laboratoryInformationService.getInformationByTime(timeHelper);
//遍历数据
for(int i=0;i<laboratoryList.size();i++){
//创建行
row = sheet.createRow(i+1);
Map<String,Object> laboratoryMap = new HashMap<String,Object>();//临时变量
laboratoryMap = (Map<String, Object>) laboratoryList.get(i);
//给每一行设置单元格
//第一列
cell = row.createCell(0);//列索引
cell.setCellValue(laboratoryMap.get("id").toString());//单元格内容
cell.setCellStyle(style);//列的样式
//第二列
cell = row.createCell(1);
cell.setCellValue(laboratoryMap.get("syncDate").toString());
cell.setCellStyle(style);
............
}
//将excel的数据写入文件
HttpServletResponse res = ServletActionContext.getResponse();
res.setContentType("octets/stream");
String excelName = "检查单";//文件名字
//转码防止乱码
try {
res.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream os;
try {
os = res.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
System.out.println("excel导出成功");
return null;//此处一定要为null否则报错
}
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/qtt1994/p/9396470.html