Java POI 超简洁的导出excel到指定路径 以及复制导出路径下的所有文件的excel到指定路径

Java POI 超简洁的导出excel到指定路径 以及复制导出路径下的所有文件的excel到指定路径

package com.qiya.springboot.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExportController {
	// 下载文件的存放路径
	private static final String rootFilePath = "F:/exportByJava/";
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * @return expResult
	 * "/" == "\\"
	 * 
	 */
	@RequestMapping("/exportUsers")
	public boolean exportUsers(HttpServletRequest request, HttpServletResponse response) {
		boolean expResult = false;
		try {
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet1 = workbook.createSheet("sheet1");
			List<Map<String, Object>> usersList = jdbcTemplate
					.queryForList("SELECT u.id,u.userName,u.userAge,u.userAddress FROM user u");
			// 设置列宽
			sheet1.setColumnWidth(0, 30*256);
			// 合并单元格   参数说明:1:开始行 2:结束行  3:开始列 4:结束列
			sheet1.addMergedRegion(new CellRangeAddress(0,0,0,3));
			
			String[] headers = {"ID", "用户名", "年龄", "地址"};
			HSSFCellStyle style = workbook.createCellStyle();
			style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm:ss"));
			HSSFFont font = workbook.createFont();
			font.setBold(true);
			style.setFont(font);
			style.setAlignment(HorizontalAlignment.CENTER);
			style.setVerticalAlignment(VerticalAlignment.CENTER);
			// 下两行共同构成了背景色
			style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
			style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
			style.setBorderTop(BorderStyle.THIN);
			
			// 第一行
			HSSFRow row0 = sheet1.createRow(0);
			HSSFCell row0cell0 = row0.createCell(0);
			HSSFRichTextString text = new HSSFRichTextString("用户表");
			row0cell0.setCellValue(text);
			row0cell0.setCellStyle(style);
			
			// 第二行
			HSSFRow row1 = sheet1.createRow(1);
			for(int i=0;i<headers.length;i++){
				HSSFCell cell = row1.createCell(i);
				HSSFRichTextString text2 = new HSSFRichTextString(headers[i]);
				cell.setCellValue(text2);
				cell.setCellStyle(style);
			}
			
			// 第三行及以后
			int rowNum = 2;
			for(Map<String, Object> uMap : usersList){
				int rowNumCellN = 0;
				HSSFRow rowRowNum = sheet1.createRow(rowNum);
				for(String uMapKey : uMap.keySet()) {
					for(;rowNumCellN < uMap.size();) {
						rowRowNum.createCell(rowNumCellN).setCellValue(String.valueOf(uMap.get(uMapKey)));
						rowNumCellN++;
						break;
					}
				}
				rowNum++;
			}			
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat formatToday = new SimpleDateFormat("yyyyMMdd");
			String date = format.format(new Date());			
			String fileName = date+"_用户表.xls";
			isDirExist(rootFilePath+formatToday.format(new Date()));
			FileOutputStream outputStream = new FileOutputStream(rootFilePath+formatToday.format(new Date())+"/"+fileName);
			workbook.write(outputStream); // 写入磁盘
			outputStream.close();
			workbook.close();
			expResult = true;
		} catch (Exception e) {
			expResult = false;
			e.printStackTrace();
		}
		return expResult;
	}
	
	/**
	 * @return 针对window.locatin.hef访问导出方法无法接收导出结果,
	 * 		此方法用来调用exportUsers以显示导出结果,前台以ajax调用此方法
	 * */
	@PostMapping("/showExpRes")
	public Map<String, Object> showExpRes(HttpServletRequest request,HttpServletResponse response) {
		boolean res = exportUsers(request, response);
		Map<String, Object> map = new HashMap<>();
		map.put("res", res);
		return map;
	}
	
	/**
	 * @return map
	 * */
	@PostMapping("/mvFile")
	public Map<String, Object> mvFile(HttpServletRequest request) {
		// windows中是反斜杠,java中是正斜杠  
		// 最好不要用get方式传带路径的参数,避免很多错误
		String fileDir = request.getParameter("fileDir");
		System.out.println(fileDir);
		Map<String, Object> resMap = new HashMap<>();
		SimpleDateFormat formatToday = new SimpleDateFormat("yyyyMMdd");
		// 待移动的文件夹
		File file = new File(rootFilePath+formatToday.format(new Date()));
		File[] fileArr = file.listFiles();
		if(fileArr == null) {
			return null;
		}
		try {
			for(File mvfile: fileArr) {
				FileInputStream in = new FileInputStream(mvfile);
				FileOutputStream out = new FileOutputStream(new File(fileDir+"/"+mvfile.getName()));
				byte[] buff = new byte[1024]; // 1kb = 1024Byte
				System.out.println("移动的文件:"+fileDir+"/"+mvfile.getName());
				int n = 0;
				while((n = in.read(buff)) != -1) {
					out.write(buff, 0, n);
				}
				out.flush();
				in.close();
				out.close();
			}
			resMap.put("success", "true");
		} catch (Exception e) {
			resMap.put("success", "false");
			e.printStackTrace();
		}		
		return resMap;
	}
	
	/**
	 * @param 当前文件夹路径
	 * */
	public void isDirExist(String fileDir) {
		File file = new File(fileDir);
		if(!file.exists()) {
			file.mkdir();
		}
	}
	
} 

html只用看导出部分就行。。。

<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-table.min.css">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-table.js"></script>
<script type="text/javascript" src="js/bootstrap-table-zh-CN.min.js"></script>

</head>
<body>
<div class="container">
	
	<!-- 信息框 -->	
	<div class="form-group">
		<button class="btn btn-success" id="heroInfo" 
		title="详细信息" data-content="女 23岁" data-placement="bottom"></button>
	</div><!-- 结束信息框 -->
	
	
	<div id="toolbar" class="btn-group">
		<button id="btn_add" type="button" class="btn btn-default" onclick="openAddModel()" >
            	<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
         </button>
         <button id="btn_edit" type="button" class="btn btn-default" onclick='updateUser()'>
             <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
         </button>
         <button id="btn_delete" type="button" class="btn btn-default" onclick='delUser()'>
             <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
         </button>
         <button type="button" class="btn btn-default" onclick="exportUsers()">            
             <span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出
         </button>             
    </div>
    <div style="float:right;margin-top: 10px;">
         <span><input type="text" id="unameCon" placeholder="请输入用户名进行查找(输入全名搜索速度更快哦!)"
         	style="width:300px; height: 34px;font-size: 12px;vertical-align:middle;border-radius:  4px;border: solid 1px #D0CDC7;" />
         </span>
         <button id="btn_search" type="button" class="btn btn-default" style="margin-left:0px" onclick="searchByCon()">
	         	<span class="glyphicon glyphicon-search" aria-hidden="true"></span>搜索
	     </button>
         	<button id="btn_reset" type="button" class="btn btn-default">
         	<span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>重置
         </button> 
     </div> 
	         
    <table id="allUsers"></table>
	
	<!-- 修改单个用户模态框 -->
	<div class="modal fade" id="openUserInfoModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					 <h4 class="modal-title" id="myModalLabel">用户信息</h4>
				</div>
				<div class="modal-body">
					<div class='table table-condensed'>
						<div style="display:none;"><input type="text" name="id" id="uid" /></div>
						<div class="form-group">用户名:<input type="text" name="name" id="unameModal" /></div>
						<div class="form-group" id="unaemErrorMsgModal"></div>
						<div class="form-group">&nbsp;&nbsp;&nbsp;&nbsp;龄:<input type="number" name="age" id="uageModal" /></div>
						<div class="form-group" id="uageErrorMsgModal"></div>
						<div class="form-group">&nbsp;&nbsp;&nbsp;&nbsp;址:<input type="text" name="address" id="uaddressModal" /></div>
						<div class="form-group" id="uaddressErrorMsgModal"></div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" onclick="saveInfo()">保存</button>
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            	</div>
			</div>
		</div>
	</div> <!-- 结束单个用户信息框修改 -->
</div>
<div>
	<button class="btn btn-info" onclick="mvFile()">移动excel到指定目录</button>
	<input type = "text" id="filePath" style="width:300px; height: 34px;font-size: 12px;vertical-align:middle;border-radius:  4px;border: solid 1px #D0CDC7;" placeholder = "请填写存放路径"/>
	<div id="showUserByPermission" style="width: 500px; margin-left: 100px;"></div>
</div>
<script>
	$(function () {
		doSearch();
		$("#heroInfo").popover({
			trigger: 'focus'
		});
	});
	
	function delUser(){
		// 获取curPage=>redis
		var page = $("#allUsers").bootstrapTable("getPage");
		var users = $("#allUsers").bootstrapTable('getSelections');
		if(users.length==0){
			alert("请选择要删除的行!");
			return;
		}
		var ids = "";
		for(var i=0;i<users.length;i++){
			if(i==users.length-1){
				ids += users[i].id;
			}else{
				ids += users[i].id+"#";
			}			
		}
		$.ajax({
			url:"/nianyu/user/delUser?curPage="+page.pageNumber,
			type:"post",
			dataType:"json",
			data:{
				"ids":ids
			},
			success:function(data){		
				var delFailCount = data.delFailCount;
				var delSuccessCount= data.delSuccessCount;
				var n = delSuccessCount-delFailCount;
				if(delSuccessCount>0){
					alert("删除成功!"+"删除成功"+delSuccessCount+"条!"+"删除失败"+delFailCount+"条!"); 
					$("#allUsers").bootstrapTable('refresh');
				}else{
					alert("删除失败!"+"删除成功"+delSuccessCount+"条!"+"删除失败"+delFailCount+"条!");
					$("#allUsers").bootstrapTable('refresh');
				}
			}
		});
		
	}
	
	function updateUser(){
		var users = $("#allUsers").bootstrapTable('getSelections');
		if(users.length==0){
			alert("请选择要修改的行!");
			return;
		}else if(users.length>1){
			alert("不能一次修改多行!");
			return;
		}else{
			$('#openUserInfoModal').modal("show");
			// 判断是否进入修改的参数,很重要,困扰了两个多小时
			istate = 0;
			$.ajax({
				url:"/nianyu/user/queryUserInfo?id="+users[0].id,
				type:"post",
				dataType:"json",
				success:function(data){							
					var user = data.res;
					$('#uid').val(user.id);
					$('#unameModal').val(user.userName);
					$('#uageModal').val(user.userAge);
					$('#uaddressModal').val(user.userAddress);
				}
			});
		}		
		
	}
	
	function openAddModel(){
		// 判断是否进入新增的参数,很重要,困扰了两个多小时
		istate = 1;
		$('#unameModal').val("");
		$('#uageModal').val("");
		$('#uaddressModal').val("");
		$('#openUserInfoModal').modal("show");
	}
	
	function saveInfo(){
		// 获取curPage=>redis
		var page = $("#allUsers").bootstrapTable("getPage");
		$("#unaemErrorMsgModal").empty();
		$("#uageErrorMsgModal").empty();
		$("#uaddressErrorMsgModal").empty();
		var uid = $('#uid').val();
		var unameModal = $('#unameModal').val();
		
		var uageModal = $('#uageModal').val();
		var uaddressModal = $('#uaddressModal').val();
		if(!unameModal){
			str = "
错误!用户名不能为空!
"
; $("#unaemErrorMsgModal").append(str); return; }else if(!uageModal){ str = "
错误!年龄不能为空!
"
; $("#uageErrorMsgModal").append(str); return; }else if(!uaddressModal){ str = "
错误!地址不能为空!
"
; $("#uaddressErrorMsgModal").append(str); return; } if(istate==1){ $.ajax({ url:"/nianyu/user/addUser?curPage="+page.pageNumber, type:"post", dataType:"json", data:{ "userName":unameModal, "userAge":uageModal, "userAddress":uaddressModal }, success:function(data){ $("#allUsers").bootstrapTable('refresh'); $('#openUserInfoModal').modal('hide'); if("success"==data.res){ alert("保存成功!"); }else{ alert("保存失败!") } } }); }else{ $.ajax({ url:"/nianyu/user/updateUserInfo?curPage="+page.pageNumber, type:"post", dataType:"json", data:{ "id":uid, "userName":unameModal, "userAge":uageModal, "userAddress":uaddressModal }, success:function(data){ $('#uid').val(''); $("#allUsers").bootstrapTable('refresh'); $('#openUserInfoModal').modal('hide'); if("success"==data.res){ alert("修改成功!"); }else{ alert("修改失败!") } } }); } } // javascript加载bootstraptable function doSearch(){ $("#allUsers").bootstrapTable({ // 对应table标签的id url: "/nianyu/user/queryUserInfoByPageRedis", // 获取表格数据的url method: 'get', //请求方式(*) toolbar: '#toolbar', //工具按钮用哪个容器 striped: true, //是否显示行间隔色 cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) sortable: false, //是否启用排序 sortOrder: "asc", //排序方式 sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*) pageNumber:1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [10], //可供选择的每页的行数(*) search: false, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大 strictSearch: false, showColumns: false, //是否显示所有的列 showRefresh: false, //是否显示刷新按钮 minimumCountColumns: 2, //最少允许的列数 clickToSelect: true, //是否启用点击选中行 height: 543, //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度 uniqueId: "ID", //每一行的唯一标识,一般为主键列 showToggle:false, //是否显示详细视图和列表视图的切换按钮 cardView: false, //是否显示详细视图 detailView: false, //是否显示父子表 queryParams: function (params) { return { pageSize: params.limit, // 每页要显示的数据条数 offset: params.offset, // 每页显示数据的开始行号 sort: params.sort, // 要排序的字段 sortOrder: params.order, // 排序规则 userName:$("#unameCon").val(), } }, columns: [ { checkbox: true, // 显示一个勾选框 align: 'center' // 居中显示 }, { field: 'number', title: '序号', align: 'center', valign: 'middle', formatter: function(value, row, index){ // 在bootstrap-table.js 中增加getPage(), var page = $("#allUsers").bootstrapTable("getPage"); return page.pageSize * (page.pageNumber - 1) + index + 1; } }, { field: 'id', title: 'ID', // 表格表头显示文字 align: 'center', // 左右居中 valign: 'middle' // 上下居中 }, { field: 'userName', // 返回json数据中的name title: '用户名', // 表格表头显示文字 align: 'center', // 左右居中 valign: 'middle' // 上下居中 }, { field: 'userAge', title: '年龄', align: 'center', valign: 'middle' }, { field: 'userAddress', title: '地址', align: 'center', valign: 'middle' }/* { title: "操作", align: 'center', valign: 'middle', width: 160, // 定义列的宽度,单位为像素px formatter: function (value, row, index) { return ''; } } */ ], onLoadSuccess: function(){ //加载成功时执行 console.info("加载成功"); }, onLoadError: function(){ //加载失败时执行 console.info("加载数据失败"); } }) } function exportUsers(){ // window.location.href = "/nianyu/exportUsers"; $.ajax({ url:"/nianyu/showExpRes", type:"post", dataType:"json", success:function(data){ if(data.res) { alert("导出成功!"); }else { alert("导出失败!"); } } }); } function searchByCon(){ if($('#unameCon').val().length > 0 ){ $("#btn_edit").attr('disabled',true); $('#btn_delete').attr('disabled',true); $("#allUsers").bootstrapTable('refresh'); }else{ $("#btn_edit").attr('disabled',false); $('#btn_delete').attr('disabled',false); $("#allUsers").bootstrapTable('refresh'); } } function mvFile() { var fileDir = $("#filePath").val(); $.ajax({ url: "/nianyu/mvFile", type:"post", dataType:"json", data:{ "fileDir":fileDir }, success:function(data){ if("true" == data.success) { alert("移动成功!"); }else { alert("移动失败!"); } } }) } </script> </body> </html>

你可能感兴趣的:(Java POI 超简洁的导出excel到指定路径 以及复制导出路径下的所有文件的excel到指定路径)