springboot -- 整合poi 实现-数据库数据逆向生成excel文件

目录:
1、poi Maven 依赖+json依赖
2、ExcelUtil 工具类及测试代码
3、JsonUtil 工具类及main测试
4、prop 配置文件 SqlConfig.properties(单纯导出数据无需配置,需修改代码逻辑)
5、读取prop 配置文件工具类 PropUtli.java(单纯导出数据无需配置)
6、Excel 生成核心类

流程:
1、获取前台传递的要导出的文件的文件名(建议定义为数据库名一致)
2、根据文件名判断查询那个表的数据(所有)
3、处理数据成生成excel 需要的格式数据
---- 3.1、读取prop 配置文件信息(表名=数据库名称,mysql=实体类名,excel=生成的excel字段名-第二行,name=字段说明-第一行 )
---- 3.2、解析json数据拼装list
4、写入生成文件路径,使用生成excel工具类生成excel 保存在服务器(重启文件会消失,在编译后的目录)
5、下载文件(导出)

不能使用ajax,不然下载的数据会返回到ajax里,导致下载失败
导出的文件xls ,为2003版,无法使用2007版解析数据,所有切勿修改为 xlsx

效果展示

以这个为例子
1、数据库数据列表
在这里插入图片描述
2、传文件名点击导出
在这里插入图片描述
3、结果excel数据
在这里插入图片描述
4、配置展示

在这里插入图片描述

1、poi Maven 依赖+json依赖

使用json 的目的是可以根据数据库的表名称来动态判断生成那个表的excel文件

	<!-- jsonObject 支持  -->
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>


        <!-- excel2003使用的包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- excel2007+使用的包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17</version>
        </dependency>

2、ExcelUtil 工具类及测试代码


	/**
	 * 对list数据源将其里面的数据导入到excel表单
	 * 
	 * @param fieldName [] 导出到excel文件里的表头名
	 * @param columnIt  [] 导出到excel文件里的表头NAME
	 * @param sheetName 工作表的名称
	 * @param sheetSize 每个sheet中数据的行数,此数值必须小于65536
	 * @param output    java输出流
	 */
	@SuppressWarnings("all")
	public static boolean exportExcel(List list, String[] fieldName, String[] columnIt, String sheetName, int sheetSize,
			OutputStream output) {
		HSSFWorkbook workbook = new HSSFWorkbook();// 产生工作薄对象
		if (sheetSize >= 65536) {
			sheetSize = 65536;
		}
		double sheetNo = Math.ceil(list.size() / sheetSize);
		for (int index = 0; index <= sheetNo; index++) {
			HSSFSheet sheet = workbook.createSheet();// 产生工作表对象
			workbook.setSheetName(index, sheetName + index);// 设置工作表的名称.
			// 产生第一行数据
			HSSFRow row = sheet.createRow(0);
			HSSFCell cell;// 产生单元格
			for (int i = 0; i < fieldName.length; i++) {
				cell = row.createCell(i); // 创建第一行各个字段名称的单元格
				// 为了能在单元格中输入中文,设置字符集为UTF_16
				// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
				// 设置单元格内容为字符串型
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(fieldName[i]); // 给单元格内容赋值
			}
			// 产生第二行数据
			HSSFRow row2 = sheet.createRow(1);
			// 写入各个字段的名称
			for (int i = 0; i < columnIt.length; i++) {
				cell = row2.createCell(i); // 创建第二行各个字段名称的单元格
				cell.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置单元格内容为字符串型

				cell.setCellValue(columnIt[i]); // 给单元格内容赋值
			}
			int startNo = index * sheetSize;
			int endNo = Math.min(startNo + sheetSize, list.size());
			// 写入各条记录,每条记录对应excel表中的一行
			for (int i = startNo; i < endNo; i++) {
				// 从第3行开始写入数据
				row = sheet.createRow(i + 2 - startNo);
				HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
				for (int j = 0; j < columnIt.length; j++) {
					cell = row.createCell(j);
					cell.setCellType(HSSFCell.CELL_TYPE_STRING);
					// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
					Object value = map.get(columnIt[j]);
					if (value != null) {
						cell.setCellValue(map.get(columnIt[j]).toString());
					} else
						cell.setCellValue("");
				}
			}
		}
		try {
			output.flush();
			workbook.write(output);
			output.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Output is closed ");
			return false;
		}
	}

	public static void main(String[] args) {
		// 初始化数据
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 10; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", i);
			map.put("name", "姓名" + i);
			list.add(map);
		}

		String[] alias = { "编号", "姓名" };// excel的列头
		String[] names = { "id", "name" };// 数据List中的Map的key值.
		FileOutputStream out = null;
		try {
			out = new FileOutputStream("d:\\success2.xls");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		exportExcel(list, alias, names, "学生信息表", 60000, out);
		System.out.println("----执行完毕----------");
	}

3、JsonUtil 工具类及main测试

如果有把 list对象 转为json的就不需要这个类了,可以用自己的方法

package com.hy.wargame.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class JsonUtil {

	/**
	 * 从json对象字符格式中得到一个java对象
	 * 
	 * @param jsonString
	 * @param objclass
	 * @return
	 */

	public static void jsonWrite(String json, HttpServletResponse response, Logger log) {
		try {
			response.setContentType("application/json; charset=UTF-8");
			System.out.println("json数据" + json);
			response.getWriter().write(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("输出json用户数据错误");
			log.error(e.getMessage());
		}
	}

	public static Object getObjectJsonString(String jsonString, Class<?> objclass) {
		Object obj;
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		obj = JSONObject.toBean(jsonObject, objclass);
		return obj;
	}

	/**
	 * 从json对象字符串格式中得到一个map对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Map<String, Object> getMapJson(String jsonString) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		Iterator<?> iter = jsonObject.keys();
		Object obj;
		Map<String, Object> valueMap = new HashMap<String, Object>();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			obj = jsonObject.get(key);
			valueMap.put(key, obj);
		}

		return valueMap;
	}

	/**
	 * 
	 * 从json对象字符串中获取一个object数组对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Object[] getObjectArrayJson(String jsonString) {
		JSONArray jsonarry = JSONArray.fromObject(jsonString);
		return jsonarry.toArray();
	}

	/**
	 * 从json对象字符串中获取一个list对象
	 * 
	 * @param jsonString
	 * @param jsonClass
	 * @return
	 */

	public static List<Object> getListJson(String jsonString, Class<?> jsonClass) {
		JSONArray jsonarray = JSONArray.fromObject(jsonString);
		// Object obj;
		// JSONObject jsonobject;
		List<Object> valueList = new ArrayList<Object>();
		for (Object object : jsonarray) {
			// jsonobject = (JSONObject) object;
			// obj = JSONObject.toBean(jsonobject, jsonClass);
			valueList.add(object);
		}
		return valueList;
	}

	/**
	 * 从json对象中获取字符串对象数组
	 * 
	 * @param jsonString
	 * @return
	 */
	public static String[] getStringArrayJson(String jsonString) {
		JSONArray jsonArray = JSONArray.fromObject(jsonString);

		String[] jsonStringArray = new String[jsonArray.size()];

		for (int i = 0; i < jsonArray.size(); i++) {
			jsonStringArray[i] = jsonArray.getString(i);
		}
		return jsonStringArray;
	}

	/**
	 * 将java类转换为json数据
	 * 
	 * @param obj
	 * @return
	 */

	public static String getJsonString(Object obj) {

		JSONObject jsonobject = null;
		try {
			JsonConfig jsonConfig = new JsonConfig();
			DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
			jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
			jsonobject = JSONObject.fromObject(obj, jsonConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return jsonobject.toString();

	}

	/**
	 * 将java数组数据转换为json数据
	 * 
	 * @param obj
	 * @return
	 */
	public static String getJsonString(Object[] obj) {
		JsonConfig jsonConfig = new JsonConfig();
		DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
		jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
		JSONArray jsonArray = JSONArray.fromObject(obj, jsonConfig);
		return jsonArray.toString();
	}

	/**
	 * 将list数据转换为json数据
	 * 
	 * @param list
	 * @return
	 */
	public static String getJsonString(List<?> list) {
		JSONArray jsonArray = null;
		try {
			JsonConfig jsonConfig = new JsonConfig();
			DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
			jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
			jsonArray = JSONArray.fromObject(list, jsonConfig);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonArray.toString();
	}

	/**
	 * 将map数据转换为json数据
	 * 
	 * @param map
	 * @return
	 */
	public static String getJsonString(Map<?, ?> map) {
		JsonConfig jsonConfig = new JsonConfig();
		DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss");
		jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);
		JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);
		return jsonObject.toString();
	}
}

json 时间数据处理工具类

package com.hy.car.utils;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
  
public class DateJsonValueProcessor implements JsonValueProcessor {   
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";   
    private DateFormat dateFormat;   
  
    /**    
     * 构造方法.    
     *    
    * @param datePattern 日期格式    
     */  
    public DateJsonValueProcessor(String datePattern) {   
        try {   
            dateFormat = new SimpleDateFormat(datePattern);   
        } catch (Exception ex) {   
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);   
        }   
    }   
  
    @Override
	public Object processArrayValue(Object value, JsonConfig jsonConfig) {   
        return process(value);   
    }   
  
    @Override
	public Object processObjectValue(String key, Object value,   
            JsonConfig jsonConfig) {   
        return process(value);   
    }   
  
    private Object process(Object value) {   
        if (value == null) {   
            value = new Date();   //为null时返回当前日期,也可以返回"",看需要   
        }   
        return dateFormat.format((Date) value);   
    }   
  
    public static String map2JSonStr(Map<?,?> map) {   
        JsonConfig jsonConfig = new JsonConfig();   
        DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor(   
                DEFAULT_DATE_PATTERN);   
        jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);   
  
        JSONObject jsonObject = JSONObject.fromObject(map, jsonConfig);   
  
        return jsonObject.toString();   
    }      
       
    //将对象转换为json string,使用上面定义的的日期格式   
    public static JSONObject obj2JsonObj(Object obj) {   
        JsonConfig jsonConfig = new JsonConfig();   
        DateJsonValueProcessor beanProcessor = new DateJsonValueProcessor(   
                DEFAULT_DATE_PATTERN);   
        jsonConfig.registerJsonValueProcessor(Date.class, beanProcessor);   
  
        JSONObject jsonObject = JSONObject.fromObject(obj, jsonConfig);   
  
        return jsonObject;   
   }   
}  

4、prop 配置文件 SqlConfig.properties

这里导出只需要 ### _mysql ,### __name,### _excel
如果说字段对应数据库对应的实体类,不需要中文描叙也可以不需要这个配置文件(需修改代码逻辑)
name=第一行的说明
excel=第二行的字段名
Achievement=AchievementConfig 文件名=数据库名

### _type  定义,对应实体类字段类型(可无视大小写,程序自动解析为小写,int,int,Short,String,Double,Float,Data)
### _mysql 定义,对应实体类或数据库字段 (大小写必须对应)
### _excel 定义,对应excel类第二行字段 (无视大小写,程序自动解析为小写)
### __name  定义,   对应excel中的第一行说明(导出excel生成数据时需要)

### 1--成就  
Achievement=AchievementConfig
Achievement_type=int,String,String,String,String,String,String
Achievement_mysql=id,fulfill,resource,num,name,`desc`,`icon`
Achievement_excel=id,fulfill,resource,num,name,desc,icon
Achievement_name=id,成就需要完成的数量(如主城升级到15级),奖励物品Id,奖励数量 ,成就标题,显示在游戏内的成就内容,成就图标

5、读取prop 配置文件工具类 PropUtli.java

package com.hy.wargame.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * 读取配置文件
 * 
 * @author wangsong
 * @date 2019年5月31日 下午7:03:14
 */
public class PropUtli {
	/**
	 * 读取配置文件
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public static String findprop(String key) {
		InputStream in = PropUtli.class.getClassLoader().getResourceAsStream("SqlConfig.properties");
		Properties prop = new Properties();
		String rw = null;
		try {
			prop.load(new InputStreamReader(in, "UTF-8"));
			rw = prop.getProperty(key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rw;
	}
}

6、Excel 生成核心类

1、获取前台传递的要导出的文件的文件名(建议定义为数据库名一致)
2、根据文件名判断查询那个表的数据(所有)
3、处理数据成生成excel 需要的格式数据
--------- 3.1、读取prop 配置文件信息(表名=数据库名称,mysql=实体类名,excel=生成的excel字段名-第二行,name=字段说明-第一行 )
--------- 3.2、解析json数据拼装list
4、写入生成文件路径,使用生成excel工具类生成excel 保存在服务器(重启文件会消失,在编译后的目录)
5、下载文件(导出)

不能使用ajax,不然下载的数据会返回到ajax里,导致下载失败

package com.hy.wargame.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hy.wargame.util.ConfigExcelUtil;
import com.hy.wargame.util.JsonUtil;
import com.hy.wargame.util.PropUtli;

/**
 * 数据库数据生成excel 文件导出
 * 
 * @author wangsong
 * @date 2019年5月22日 上午11:50:55
 */
@Controller
@RequestMapping("/file")
public class ExcelController extends BaseController {

	
	
	/**
	 * 导出为excel文件
	 * 
	 * @author wangsong
	 * @return
	 * @date 2019年6月15日 下午4:32:37
	 * @return http://localhost:88/downloadExcel?fileName=Achievement
	 */
	@RequestMapping("/downloadExcel")
	@ResponseBody
	public void downloadExcel(HttpServletResponse response, String fileName) {
		try {
			// 数据库查询的json字符串
			String jsonStr = findAll(fileName);
			// json 轉為 list
			List<Object> listJson = JsonUtil.getListJson(jsonStr, List.class);
			// 解析成生成格式excel的数据
			Map<String, Object> resMap = dataExcel(listJson, fileName);
			// 生成excel
			String pathFile = generateExcel(resMap, fileName);
			// 下載
			downloadFile(response, pathFile, fileName);
			// return "success";
		} catch (Exception e) {
			e.printStackTrace();
			// return "导出失败";
		}
	}
	
	
	


	/**
	 * 动态查询数据库数据返回json串(根据数据库名称判断)
	 * 
	 * @author wangsong
	 * @return
	 * @date 2019年6月15日 下午4:49:55
	 */
	private String findAll(String fileName) {
		String json = "";
		if (fileName.equals("Achievement")) {
			json = JsonUtil.getJsonString(achievementService.findAll());
		} else if (fileName.equals("Arena")) {
			json = JsonUtil.getJsonString(sportsRewardConfigService.findAll());
		} else if (fileName.equals("Artifact")) {
			json = JsonUtil.getJsonString(artifactConfigService.findAll());
		} else if (fileName.equals("Activity")) {
			json = JsonUtil.getJsonString(activityConfigService.findAll());
		} else if (fileName.equals("ActivityReward")) {
			json = JsonUtil.getJsonString(activityRewardConfigService.findAll());
		} else if (fileName.equals("Challenge")) {
			json = JsonUtil.getJsonString(challengeConfigService.findAll());
		} else if (fileName.equals("AltarShop")) {
			json = JsonUtil.getJsonString(altarShopService.findAll());
		} else if (fileName.equals("BeginGuide")) {
			json = JsonUtil.getJsonString(beginGuideConfigService.findAll());
		} else if (fileName.equals("Build")) {
			json = JsonUtil.getJsonString(buildConfigService.findAll());
		} else if (fileName.equals("BuildHelp")) {
			json = JsonUtil.getJsonString(buildHelpConfigService.findAll());
		} else if (fileName.equals("BuildUp")) {
			json = JsonUtil.getJsonString(buildUpConfigService.findAll());
		} else if (fileName.equals("CampBonus")) {
			json = JsonUtil.getJsonString(campBonusConfigService.findAll());
		} else if (fileName.equals("Challengereward")) {
			json = JsonUtil.getJsonString(challengeRewardConfigService.findAll());
		} else if (fileName.equals("Equip")) {
			json = JsonUtil.getJsonString(equipConfigService.findAll());
		} else if (fileName.equals("TipsInfo")) {
			json = JsonUtil.getJsonString(tipsInfoConfigService.findAll());
		} else if (fileName.equals("VIP")) {
			json = JsonUtil.getJsonString(vipConfigService.findAll());
		} else if (fileName.equals("HeroUpResInfo")) {
			json = JsonUtil.getJsonString(heroUpResConfigService.findAll());
		} else if (fileName.equals("transform")) {
			json = JsonUtil.getJsonString(transFormConfigService.findAll());
		} else if (fileName.equals("BackendErrorMessage")) {
			json = JsonUtil.getJsonString(backendErrorMessageConfigService.findAll());
		} else if (fileName.equals("Sensitiveword")) {
			json = JsonUtil.getJsonString(sensitivewordConfigService.findAll());
		} else if (fileName.equals("TavernBag")) {
			json = JsonUtil.getJsonString(heroGiftConfigService.findAll());
		} else if (fileName.equals("MapReward")) {
			json = JsonUtil.getJsonString(mapRewardConfigService.findAll());
		} else if (fileName.equals("HeroTraining")) {
			json = JsonUtil.getJsonString(heroTrainConfigService.findAll());
		} else if (fileName.equals("Shop")) {
			json = JsonUtil.getJsonString(shopConfigService.findAll());
		} else if (fileName.equals("LineUp")) {
			json = JsonUtil.getJsonString(lineUpConfigService.findAll());
		} else if (fileName.equals("SevenActivity")) {
			json = JsonUtil.getJsonString(sevenActivityConfigService.findAll());
		} else if (fileName.equals("Task")) {
			json = JsonUtil.getJsonString(taskConfigService.findAll());
		} else if (fileName.equals("Gem")) {
			json = JsonUtil.getJsonString(gemConfigService.findAll());
		} else if (fileName.equals("Resource")) {
			json = JsonUtil.getJsonString(resConfigService.findAll());
		} else if (fileName.equals("SkillData")) {
			json = JsonUtil.getJsonString(skillDataConfigService.findAll());
		} else if (fileName.equals("SignIn")) {
			json = JsonUtil.getJsonString(signInConfigService.findAll());
		} else if (fileName.equals("Wishing")) {
			json = JsonUtil.getJsonString(wishingConfigService.findAll());
		} else if (fileName.equals("Market")) {
			json = JsonUtil.getJsonString(marketConfigService.findAll());
		} else if (fileName.equals("Prophet")) {
			json = JsonUtil.getJsonString(prophetConfigService.findAll());
		} else if (fileName.equals("Skill")) {
			json = JsonUtil.getJsonString(skillConfigService.findAll());
		} else if (fileName.equals("HeroesPieces")) {
			json = JsonUtil.getJsonString(heroesPiecesConfigService.findAll());
		} else if (fileName.equals("MapPoint")) {
			json = JsonUtil.getJsonString(mapPointConfigService.findAll());
		} else if (fileName.equals("Randomname")) {
			json = JsonUtil.getJsonString(randomnameConfigService.findAll());
		} else if (fileName.equals("Gift")) {
			json = JsonUtil.getJsonString(giftConfigService.findAll());
		} else if (fileName.equals("Plot")) {
			json = JsonUtil.getJsonString(plotConfigService.findAll());
		} else if (fileName.equals("OnlineInfo")) {
			json = JsonUtil.getJsonString(onLineConfigService.findAll());
		} else if (fileName.equals("Reward")) {
			json = JsonUtil.getJsonString(rewardConfigService.findAll());
		} else if (fileName.equals("TavernRecruit")) {
			json = JsonUtil.getJsonString(heroRecruitConfigService.findAll());
		} else if (fileName.equals("HeroDestroyInfo")) {
			json = JsonUtil.getJsonString(heroDestroyConfigService.findAll());
		} else if (fileName.equals("MapResource")) {
			json = JsonUtil.getJsonString(mapResourceConfigService.findAll());
		} else if (fileName.equals("TrialTower")) {
			json = JsonUtil.getJsonString(trialConfigService.findAll());
		} else if (fileName.equals("Growcase")) {
			json = JsonUtil.getJsonString(growcaseConfigService.findAll());
		} else if (fileName.equals("SpineMode")) {
			json = JsonUtil.getJsonString(spineModeConfigService.findAll());
		} else if (fileName.equals("HelperTopic")) {
			json = JsonUtil.getJsonString(helperInfoConfigService.findAll());
		} else if (fileName.equals("Map")) {
			json = JsonUtil.getJsonString(mapConfigService.findAll());
		} else if (fileName.equals("MapLevel")) {
			json = JsonUtil.getJsonString(mapLevelConfigService.findAll());
		} else if (fileName.equals("HeroInfo")) {
			json = JsonUtil.getJsonString(heroConfigService.findAll());
		} else if (fileName.equals("HeroLevelRule")) {
			json = JsonUtil.getJsonString(heroLevelConfigService.findAll());
		}
		return json;
	}

	
	
	
	
	/**
	 * 解析成 - 生成 excel 格式的数据
	 * 
	 * @author wangsong
	 * @date 2019年6月15日 下午4:49:55
	 * @param resMap=excel数据: datas=第三行开始的数据,fieldName=第一行的字段说明,columnIt=第二行的字段
	 */
	private Map<String, Object> dataExcel(List<Object> listJson, String fileName) {
		// 返回数据
		Map<String, Object> resMap = new HashMap<String, Object>();
		// 第三行开始的数据
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		// 第一行的字段说明
		String fieldName[] = new String[30];
		// 第二行的字段,数据List中的Map的key值 = excel的列头,没有超过30个字段的表吧
		String columnIt[] = new String[30];
		// 获取表信息
		String[] sqls = PropUtli.findprop(fileName + "_mysql").split(",");
		String[] excels = PropUtli.findprop(fileName + "_excel").split(",");
		String[] nameprops = PropUtli.findprop(fileName + "_name").split(",");
		boolean resutl = true;
		for (int j = 0; j < listJson.size(); j++) {
			String valueOf = String.valueOf(listJson.get(j));
			Map<String, Object> mapJson = JsonUtil.getMapJson(valueOf);
			Map<String, Object> map = new HashMap<String, Object>();
			for (String key : mapJson.keySet()) {
				// 第一次放入第一行的说明和,第二行的字段
				if (resutl) {
					// 获得对应的excel字段(根据配置顺序判断)
					for (int i = 0; i < sqls.length; i++) {
						String sqlval = sqls[i];
						String substr = sqlval.substring(0, 1);
						if (substr.equals("`")) {
							sqlval = sqlval.substring(1, sqlval.length() - 1);
						}
						if (key.equals(sqlval)) {
							columnIt[i] = excels[i];
							fieldName[i] = nameprops[i];
						}
					}
				}
				// 放入每行的每一個數據
				map.put(key, mapJson.get(key));
			}
			resutl = false;
			datas.add(map);
		}
		resMap.put("datas", datas);
		resMap.put("columnIt", columnIt);
		resMap.put("fieldName", fieldName);
		return resMap;
	}
	
	
	
	

	/**
	 * 生成临时excel文件保存至服务器
	 * 
	 * @author wangsong
	 * @date 2019年6月17日 上午10:18:30
	 * @param resMap   文件数据内容
	 * @param fileName 文件名
	 * @return filepath 路径
	 */
	@SuppressWarnings("unchecked")
	private String generateExcel(Map<String, Object> resMap, String fileName) {
		// 文件生成路径
		String filepath = "";
		FileOutputStream out = null;
		try {
			// 获取跟目录
			File path = new File(ResourceUtils.getURL("classpath:").getPath());
			if (!path.exists())
				path = new File("");
			File upload = new File(path.getAbsolutePath(), filepath);
			if (!upload.exists())
				upload.mkdirs();
			// 指定路径
			filepath = upload + "\\" + fileName + ".xls";
			out = new FileOutputStream(filepath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// datas第三行开始的数据,fieldName第一行的说明,columnIt第二行的字段名
		List<Map<String, Object>> datas = (List<Map<String, Object>>) resMap.get("datas");
		String fieldName[] = (String[]) resMap.get("fieldName");
		String columnIt[] = (String[]) resMap.get("columnIt");
		// 生成excel
		ConfigExcelUtil.exportExcel(datas, fieldName, columnIt, fileName, 60000, out);
		// System.out.println(filepath);
		// System.out.println("----执行完毕----------");
		return filepath;
	}

	
	
	
	
	/**
	 * 文件下载
	 * 
	 * @author wangsong
	 * @date 2019年6月17日 上午11:30:07
	 * @param response
	 * @param filePath 文件路径
	 * @param fileName 下载的后的文件名称
	 */
	private static void downloadFile(HttpServletResponse response, String filePath, String fileName) {
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			// 信息头: 会告诉浏览器这个文件的名字和类型(必须设置)
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			// 指定文件下载后的名称 --> 下载名中文乱码解决 --> java.net.URLEncoder.encode(fileXsl, "UTF-8")
			response.setHeader("Content-Disposition",
					"attachment; filename=" + java.net.URLEncoder.encode(fileName + ".xls", "UTF-8"));
			os = response.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			byte[] buff = new byte[1024];
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值