java生成excel

本文介绍如何使用Java POI库创建Excel文件并设置工作表的样式、列宽、字体及表头,同时实现表头的合并单元格效果,并提供文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HSSFSheet sheet = wb.createSheet(sheetName); 
  //设置列的宽度
  sheet.setColumnWidth((short)0, (short) 2000);
  sheet.setColumnWidth((short)1, (short) 7000);
  sheet.setColumnWidth((short)2, (short) 4000);
  sheet.setColumnWidth((short)3, (short) 15000);
  sheet.setColumnWidth((short)4, (short) 4000);
  sheet.setColumnWidth((short)5, (short) 5000);
  //表头字体
  HSSFFont fontTitle=wb.createFont();
  fontTitle.setFontName(HSSFFont.FONT_ARIAL);//字体
  fontTitle.setFontHeightInPoints((short) 16);//字号
  fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
  fontTitle.setColor(HSSFColor.BLACK.index);//颜色
  fontTitle.setBoldweight((short)50); 
  //表头样式
   HSSFCellStyle centerStyle = wb.createCellStyle();//设置为水平居中 
   centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
  centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  centerStyle.setFont(fontTitle);
  //设置表头
  //合并单元格
  Region region=new Region(0, (short)0, 0, (short)5); 
  sheet.addMergedRegion(region);
  HSSFRow rowTitle = sheet.createRow( (0));
  rowTitle.setHeight((short)600);
  HSSFCell cellTitle = rowTitle.createCell((short)0);
  cellTitle.setCellStyle(centerStyle);
  cellTitle.setCellValue("XXXXXXXXXXXXXX表头");

 

 

try {
   HSSFWorkbook wb = importExcelBO.exportTemplet(modelName);
   String filename = "xls名称";
   //为了解决下载文件名中有中文的解决办法
   String tempStr = new String(filename.getBytes("GBK"), "ISO8859_1");
   response.setContentType("application/msexcel");
   // 可以通过设置default file name来确定保存文当时的建议名称。
   response.setHeader("Content-disposition", "attachment; filename="
     + tempStr + ".xls");
   ServletOutputStream os = response.getOutputStream();
   wb.write(os);
   os.flush();
   os.close();
   // 返回到列表页面
   return mapping.findForward("exportsuccess");
  } catch (Exception e) {
   generalError(request, e);
   e.printStackTrace();
   return mapping.findForward(FAIL);
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值