SSM+POI上传读取导出excel--------导出(一)

其实会了上传之后,大致的导出功能也能实现了,只是一些细节问题比较麻烦

先上传一份粗糙点的,只是实现功能,导出的xlsx版本

jsp

	<button id="btn2">导出excel</button>

$("#btn2").click(function(){
			$.ajax({
				type:'post',
				url:'exportExcel',
				success:function(data){
					if(data.code==100){
						alert("100");
					}else{
						alert("200");
					}
				},
				error:function(){
					alert("error");
				}
			})
		});

 

controller

@RequestMapping(value="/exportExcel",method=RequestMethod.POST)
	@ResponseBody
	public Msg exportExcel() {
		String path="E:\\download\\downExcel.xlsx";
		FileOutputStream out=null;
		try {
			out=new FileOutputStream(path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return Msg.fail().add("error", "文件夹不存在");
		}
		
		List list=new ArrayList();
		list=userService.findList(null);
	
		ExcelUtil.createExcel(list, out);
		
		return Msg.success();
	}

ExcelUtil.createExcel

虽然只是实现基本功能,但是这里的代码两个循环有一点重复了,等后续版本优化

list就是数据库查询出的需要导出的数据,out输出流

public static void createExcel(List list,OutputStream out) {
		XSSFWorkbook workbook=new XSSFWorkbook();
		Sheet sheet=workbook.createSheet();
		
		//先设置excel的列名
		Row row0=sheet.createRow(0);
		Object object0=list.get(0);
		for(Field field:object0.getClass().getDeclaredFields()) {
			field.setAccessible(true);
			String propertyName=field.getAnnotation(Excel.class).name();
			
			System.out.print("设置列名++++");
			System.out.print(propertyName+"===");
			
			int columnNum=field.getAnnotation(Excel.class).columnIndex();
			if(columnNum==-1)
				continue;
			row0.createCell(columnNum).setCellValue(propertyName);		
		}
		
		System.out.println("列名设置完毕,开始设置cell值");
		
		int rowNum=1;
		for(Object o:list) {
			Row row=sheet.createRow(rowNum);
			for(Field field:object0.getClass().getDeclaredFields()) {
				field.setAccessible(true);
				int columnNum=field.getAnnotation(Excel.class).columnIndex();
				if(columnNum==-1)
					continue;
				try {
					if(field.get(o)==null)
						continue;
					row.createCell(columnNum).setCellValue(field.get(o).toString());
				} catch (Exception e) {
					e.printStackTrace();
				} 		
			}
			rowNum++;
		}
		
		try {
			workbook.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}

导出效果,cell空着是因为数据库里本来就是空的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值