jsp中做导出功能

在jsp中首先应该实现form表格
<form style="margin-top: 20px;" method="get" id="Form">
<div class="main">
<div class="indexBg">
<div class="pageBox">
<div class="inputBox clearfix">
<!-- 需要在写一个连接 -->
<input type="button" value="导出" class="daochu" οnclick="exportData('/manage.onigiri/customerServiceInviteInfo/export')"/>

//在这里实现点击事件 下面用jquery来实现action
var f=$("#Form");
exportData = function(action){
$(f).attr('action', action);
$(f).attr('target', '_blank');
$(f).attr('method', 'post');
$(f).submit()
$(f).attr('action', '');
$(f).attr('target', '');
$(f).attr('method', 'get');
}

后来逻辑处理 spring的配置这里就不说了 访问action 然后通过http协议访问后台处理
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping(value="/export",method={RequestMethod.POST,RequestMethod.GET})
public void exportsalesPerformanceList(HttpServletRequest request,HttpServletResponse response){
log.info("------------导出所有的销售业绩-------");
Map map=new HashMap();
map.put("pageNum", 1);
map.put("pageSize", Integer.MAX_VALUE);
RestClientRequest rest=new RestClientRequest();
List<Map> list=new ArrayList<Map>();
/**
* 查询销售业绩 明细
*/
Map userInviteMap=new HashMap();
//这里是用来访问后台数据的 具体配置没有在这里提现
userInviteMap = rest.restSubmitJson(BaseAction.SELECT_SALESPERFORMANCE,map);
if(ResultUtil.isSuccess(userInviteMap)){
userInviteMap=(Map) ResultUtil.getResult(userInviteMap);
//初始值为0 邀请人初始值总计
int inviteCount=0;
//一度年化总额初始值为0
Double annualInvest=0.0;
//一度邀请佣金
Double commissonMoney=0.0;
//二度邀请人数
int secondaryInvestCount=0;
//二度年化投资额
Integer totalSecondAnnualInvestMoney=0;
//二度 邀请佣金
Double secondaryCommissonMoney=0.0;

Map selectMap= new HashMap();
ArrayList selectlist=(ArrayList) userInviteMap.get("list");
//下面是从数据库中拿到数据遍历 先是list然后map 强制转换成其他类型
System.out.println("-----------------------------"+selectlist.size());
for(int i=0;i<selectlist.size();i++){
//一度总人数的添加
inviteCount=inviteCount+(Integer) ((Map) selectlist.get(i)).get("inviteCount");
//一度年化总额
annualInvest=annualInvest+(Double) ((Map) selectlist.get(i)).get("annualInvest");
//一度邀请佣金
commissonMoney=commissonMoney+(Double) ((Map) selectlist.get(i)).get("commissonMoney");
//二度总人数的添加
secondaryInvestCount=secondaryInvestCount+(Integer) ((Map) selectlist.get(i)).get("secondaryInvestCount");
//二度年化投资额
totalSecondAnnualInvestMoney=totalSecondAnnualInvestMoney+(Integer) ((Map) selectlist.get(i)).get("totalSecondAnnualInvestMoney");
//二度邀请佣金
secondaryCommissonMoney=secondaryCommissonMoney+(Double) ((Map) selectlist.get(i)).get("secondaryCommissonMoney");



}
/*System.out.println(Inviteindex);
System.out.println(annualInvest);
System.out.println(commissonMoney);
System.out.println(secondaryInvestCount);
System.out.println(totalSecondAnnualInvestMoney);
System.out.println(secondaryCommissonMoney);
System.out.println(Inviteindex);*/
request.setAttribute("salesPerformance", userInviteMap);
list.addAll((List<Map>)userInviteMap.get("list"));

Map zongjieMap=new HashMap();
zongjieMap.put("realName","总计");
zongjieMap.put("ukey1", "--");
zongjieMap.put("inviteCount",inviteCount);
zongjieMap.put("annualInvest", annualInvest);
zongjieMap.put("commissonRate", "--");
zongjieMap.put("commissonMoney",commissonMoney);
zongjieMap.put("secondaryInvestCount", secondaryInvestCount);
zongjieMap.put("totalSecondAnnualInvestMoney",totalSecondAnnualInvestMoney);
zongjieMap.put("secondaryCommissonRate","--" );
zongjieMap.put("secondaryCommissonMoney",secondaryCommissonMoney );
zongjieMap.put("investUserId", "--");
list.add(zongjieMap);
/*log.info(list.toString());*/
}


Map header=new LinkedHashMap();
header.put("realName","姓名");
header.put("ukey1","邀请码");
header.put("inviteCount","一度邀请人数");
header.put("annualInvest","一度年化投资额");
header.put("commissonRate","一度邀请佣金比例");
header.put("commissonMoney","一度邀请佣金");
header.put("secondaryInvestCount","二度邀请人数");
header.put("totalSecondAnnualInvestMoney","二度年化投资额");
header.put("secondaryCommissonRate","二度邀请佣金比例");
header.put("secondaryCommissonMoney","二度邀请佣金");
header.put("investUserId","详情");



byte[] b;
try {
//这里用的是插件处理
b=ExcelUtil.exportAsBytes(list, header);
OutputStream out=null;
response.setHeader("content-disposition", "attachment;filename=salesPerformance.xlsx");
response.setContentType("application/x-excel");
response.setCharacterEncoding("UTF-8");
out = response.getOutputStream();
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
log.error("导出销售业绩..", e);
}
}

//简单的将插件处理类写下


public class ExcelUtil {

private static Logger log = LoggerFactory.getLogger(ExcelUtil.class);


@SuppressWarnings("rawtypes")
public static Workbook createWorkbook(List<Map> list, Map header) throws Exception{
// 声明一个工作薄
Workbook workbook = new SXSSFWorkbook(1000);

log.info("创建工作簿,共{}行数据", list != null ? list.size() : 0);
// 生成一个表格
Sheet sheet = workbook.createSheet();
log.info("创建表格,表头:{}", header);

list.add(0, header);

Row row = null;
Cell cell = null;
log.info("开始写入数据");
for(int i =0 ; i < list.size(); i++){
row = sheet.createRow(i);
Map map = list.get(i);
int num = 0;
Iterator it = header.keySet().iterator();
while(it.hasNext()){
cell = row.createCell(num++);
Object key = it.next();
Object value = map.get(key);
cell.setCellValue(parseCellValue(value));
}
if((i+1)%1000 == 0){
log.info("已写入{}行数据", i + 1);
}
}
log.info("数据写入完成");
return workbook;
}


/**
* @Description 将文件写入磁盘
* @author baiyanbing
* @date 2016年6月3日下午6:02:36
* @param filepath 写入磁盘路径
* @param workbook excel文件
* @throws Exception
*/
public static void writeToDisk(String filepath, Workbook workbook) throws Exception{
log.info("文件写入磁盘路径:{}", filepath);
OutputStream os = null;
try {
File file = new File(filepath);
os = new FileOutputStream(file);
workbook.write(os);
os.flush();
} catch (Exception e) {
log.error("文件写入磁盘失败", e);
throw e;
} finally{
IOUtils.closeQuietly(os);
}
}

public static void exportToDisk(String filepath, List<Map> list, Map header) throws Exception{
log.info("开始导出数据,共 {} 条数据", list.size());
long b = System.currentTimeMillis();
Workbook workbook = createWorkbook(list, header);
writeToDisk(filepath, workbook);
long a = System.currentTimeMillis();
log.info("导出结束,用时{}秒,导出路径{}", (a-b)/1000.0, filepath);
}

public static byte[] exportAsBytes(List<Map> list, Map header) throws Exception{
ByteArrayOutputStream baos = null;
try{
baos = new ByteArrayOutputStream();
Workbook workbook = createWorkbook(list, header);
workbook.write(baos);
byte[] b = baos.toByteArray();
IOUtils.closeQuietly(baos);
return b;
}catch(Exception e){
return null;
} finally {
IOUtils.closeQuietly(baos);
}
}


public static void main(String[] args) throws Exception {
Map<String, Object> header = new HashMap<String, Object>();
header.put("id", "ID");
header.put("name", "姓名");
header.put("age", "年龄");
header.put("addr", "地址");


List<Map> list = new LinkedList<Map>();
for(int i = 0 ; i <=1000; i++){
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", i);
map.put("name", "name_"+ i);
map.put("age", "age_"+i);
map.put("addr", "addr_"+i);
list.add(map);
}

// exportToDisk("D:\\g.xlsx", list, header);


DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.FLOOR);
Object d = 22213223131318.9594121231;
System.out.println(df.format(d));

NumberFormat nf = NumberFormat.getInstance();
// nf.setMaximumFractionDigits(2);
// nf.setGroupingUsed(false);
// nf.setRoundingMode(RoundingMode.FLOOR);
System.out.println(nf.format(d));

}


private static String parseCellValue(Object value){

if(value == null){
return "";
}
if(value instanceof Double){
return new BigDecimal((Double) value).setScale(2, RoundingMode.HALF_UP).toString();
}
return ObjectUtils.toString(value);
}



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值