JavaWeb中导出excel文件的简单方法

作者:jingxian 时间:2023-11-13 02:41:43 

在平时做系统项目时,经常会需要做导出功能,不论是导出excel,还是导出cvs文件。我下面的demo是在springmvc的框架下实现的。

1.JS中只需要用GET模式请求导出就可以了:


$('#word-export-btn').parent().on('click',function(){
var promotionWord = JSON.stringify($('#mainForm').serializeObject());
location.href="${ctx}/promotionWord/export?promotionWord="+promotionWord;
});

2.在controller中要做的是将文件以数据流格式输出:


 @RequestMapping("/export")
 public void export(HttpSession session, String promotionWord, HttpServletRequest request, HttpServletResponse response) throws IOException {
   User sessionUser = (User) session.getAttribute("user");
   JSONObject jsonObj = JSONObject.parseObject(promotionWord);
   HSSFWorkbook wb = promotionWordService.export(sessionUser.getId(), jsonObj);
   response.setContentType("application/vnd.ms-excel");
   Calendar cal = Calendar.getInstance();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   String fileName = "word-" + sdf.format(cal.getTime()) + ".xls";
   response.setHeader("Content-disposition", "attachment;filename=" + fileName);
   OutputStream ouputStream = response.getOutputStream();
   wb.write(ouputStream);
   ouputStream.flush();
   ouputStream.close();
 }

3.在service中需要将数据写入到格式文件中:


public HSSFWorkbook export(String userId, JSONObject jsonObj) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("word");
HSSFRow row = sheet.createRow(0);
   HSSFCellStyle style = wb.createCellStyle();
   style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
List<PromotionWord> pWordList;
Map<String, Object> map = new HashMap<>();
map.put("userId", userId);
map.put("checkExistRule", jsonObj.getString("checkExistRule"));
map.put("status", jsonObj.getString("status"));
map.put("qsStar", jsonObj.getString("qsStar"));

map.put("impressionCount", jsonObj.getString("impressionCount"));

map.put("selectGroupId", jsonObj.getString("selectGroupId"));
map.put("isCheck", jsonObj.getString("isCheck"));
map.put("word", jsonObj.getString("word"));

Long impression = jsonObj.getLong("impressionCount");
Long click = jsonObj.getLong("clickCount");
if(impression != null){
PromotionWord word = new PromotionWord();
word.setCreatedBy(userId);
word.setImpressionCount7(impression);
pWordList = getTwentyPercentlists(word);
if(pWordList != null && pWordList.size() > 0){
map.put("impressionCount", pWordList.get(pWordList.size()-1).getImpressionCount());
}else{
map.put("impressionCount", 1);
}
}else if(click != null){
PromotionWord word = new PromotionWord();
word.setCreatedBy(userId);
word.setClickCount7(click);
pWordList = getTwentyPercentlists(word);
if(pWordList != null && pWordList.size() > 0){
map.put("clickCount", pWordList.get(pWordList.size()-1).getClickCount());
}else{
map.put("clickCount", 1);
}
}

List<PromotionWord> list = commonDao.queryList(PROMOTION_WORD_DAO + ".queryExportDataByUser", map);

String[] excelHeader = {"关键词", "价格","搜索热度","推广评分","购买热度","曝光量","点击量","点击率","推广时长","花费","平均点击花费","匹配产品数","预估排名","状态"};
for (int i = 0; i < excelHeader.length; i++) {
     HSSFCell cell = row.createCell(i);
     cell.setCellValue(excelHeader[i]);
     cell.setCellStyle(style);
     if(i == 0){
     sheet.setColumnWidth(0, 30*256);
     }else{      
     sheet.setColumnWidth(i, 10*256);
     }
   }
if(list != null && list.size() > 0)
for (int i = 0; i < list.size(); i++) {
     row = sheet.createRow(i + 1);
     PromotionWord word = list.get(i);
     row.createCell(0).setCellValue(word.getWord());
     row.createCell(1).setCellValue(word.getPrice()+"");
     row.createCell(2).setCellValue(word.getSearchCount());
     row.createCell(3).setCellValue(word.getQsStar());
     row.createCell(4).setCellValue(word.getBuyCount());
     row.createCell(5).setCellValue(word.getImpressionCount7());
     row.createCell(6).setCellValue(word.getClickCount7());
     if(word.getClickCount7() == 0L){
     row.createCell(7).setCellValue("0.00%");
     }else{
     DecimalFormat df = new DecimalFormat("0.00%");
     row.createCell(7).setCellValue(df.format((Double.valueOf(word.getClickCount7())/Double.valueOf(word.getImpressionCount7()))));
     }
     row.createCell(8).setCellValue(word.getOnlineTime7());
     row.createCell(9).setCellValue(word.getCost7()+"");
     row.createCell(10).setCellValue(word.getAvgCost7()+"");
     row.createCell(11).setCellValue(word.getMatchCount());
     String rank = "";
     if(word.getMatchCount() != null && word.getMatchCount() != 0){
     if(word.getProspectRank() == null || word.getProspectRank() == 0L){      
      rank = "其他位置";
      }else{
      rank = "第"+word.getProspectRank()+"位";
      }
     }else{
     rank = "---";
     }

row.createCell(12).setCellValue(rank);
     row.createCell(13).setCellValue(word.getStatus() == 1 ?"暂停":"启动");
   }

return wb;
}

这样之后就可以直接点击导出就有效果了。

标签:java,web,导出,excel
0
投稿

猜你喜欢

  • Android中使用Bitmap类将矩形图片转为圆形的方法

    2022-01-04 18:47:40
  • spring boot 注入 property的三种方式(推荐)

    2023-01-23 05:10:27
  • 游戏开发之随机概率的选择算法

    2022-08-26 13:21:09
  • C#实现过滤sql特殊字符的方法集合

    2022-01-30 23:58:04
  • springboot项目快速搭建的方法步骤

    2021-11-07 04:55:51
  • C# Chart控件标记问题详解

    2023-01-23 03:37:35
  • java集合继承关系图分享

    2023-04-25 17:17:23
  • Android实现悬浮窗的简单方法实例

    2023-06-17 18:11:02
  • C#/VB.NET 在PDF中添加文件包(Portfolio)的方法

    2023-08-28 03:01:18
  • C#图片切割、图片压缩、缩略图生成代码汇总

    2022-01-20 07:51:26
  • C#中常用的正则表达式实例

    2021-05-27 04:39:12
  • java使用IO流对数组排序实例讲解

    2023-09-04 02:24:19
  • Android 7.0行为变更 FileUriExposedException解决方法

    2023-07-28 01:38:29
  • java微信公众号支付示例详解

    2023-11-15 05:52:01
  • Java实现简单通讯录管理系统

    2022-06-28 01:15:54
  • SpringMVC框架实现图片上传与下载

    2022-01-12 23:50:52
  • 详细解读JAVA多线程实现的三种方式

    2022-01-14 04:35:31
  • Mybatis拦 截 器实现数据权限的示例代码

    2023-11-19 20:15:04
  • Android中自定义进度条详解

    2022-11-10 00:27:52
  • 详解Java中使用泛型实现快速排序算法的方法

    2022-04-28 09:47:00
  • asp之家 软件编程 m.aspxhome.com