JavaWeb中导出excel文件的简单方法
作者:jingxian 发布时间:2023-11-13 02:41:43
标签:java,web,导出,excel
在平时做系统项目时,经常会需要做导出功能,不论是导出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;
}
这样之后就可以直接点击导出就有效果了。
0
投稿
猜你喜欢
- ArrayList的构造方法(前置知识)可快速过一些基本成员变量:// 默认初始大小private static final int DEF
- Hibernate是一个彻底的ORM(Object Relational Mapping,对象关系映射)开源框架。我们先看一下官方文档所给出
- 1.需要的Maven依赖// 支付宝<dependency> <groupId>com.alipay.
- 1. 创建全局异常处理器类GlobalExceptionHandler@ControllerAdvice: 定义统一的异常处理类,捕获 Co
- 主要从以下十几个方面对Hibernate做总结,包括Hibernate的检索方式,Hibernate中对象的状态,Hibernate的3种检
- mybatis update并非所有字段需要更新mybatis update需求:更新字段作为参数,未更新字段不传入解决办法<upda
- 先上效果图: 工具类在解析的过程中,我们会和byte做各种运算,所以我定义了一个byte工具类ByteUtils:using Sy
- public static String toUtf8String(String s) {
- 本文实例讲述了Android游戏开发学习之引擎用法。分享给大家供大家参考。具体如下:汽车引擎是汽车的心脏,其决定了汽车的性能和稳定性,是人们
- jwt简介冒泡排序:(Bubble Sort)是一种简单的交换排序。之所以叫做冒泡排序,因为我们可以把每个元素当成一个小气泡,根据气泡大小,
- Java 内存划分: 在Java内存分配中,java将内存分为:方法区,堆,虚拟机栈,本地方法栈,程序计
- 在看别人的关于CopyOnWriteArrayList 这个类的时候,看到有人提出了关于:数组拷贝的方法Arrays.copyOf() 的问
- 使用AS创建ADIL文件时AS会在main文件夹下给我们生成一个aidl文件夹和一个相同包名的包,通常我们会把所有和ADIL相关的类或文件放
- Nashorn是什么Nashorn,发音“nass-horn”,是德国二战时一个坦克的命名,同时也是java8新一代的javascript引
- 1. JNI简介JNI是Java Native Interface的英文缩写,意为Java本地接口。问题来源:由于Java编写底层的应用较难
- 我的电脑环境win10vscode 1.36.1vscode安装插件安装完这个插件后会提示你安装 platformIOCore,按照提示安装
- 假设下面是你的视频网站链接列表,如果别人想爬取你的数据十分轻松,看规则就知道数据库是序列自增的http://www.xxxx.com/vid
- 1.概念a.是个二叉树(每个节点最多有两个子节点)b.对于这棵树中的节点的节点值左子树中的所有节点值 < 根节点 < 右子树的所
- Result可以设定全局结果集,如:<struts> <constant name="struts
- 1、简单又有效的方法是使用PreparedStatement采用预编译语句集,它内置了处理SQL注入的能力,只要使用它的setXXX(如:s