Excel导入导出mysql

1,导入

public Object importToData(MultipartFile file){
		
				        HashMap<String, Object> result = new HashMap<>();
				String filename = file.getOriginalFilename();
				// 获取文件后缀名,判断是否为xlsx格式
				String suffix = filename.substring(filename.lastIndexOf(".") + 1);
				//拼接文件名,filename+time
				StringBuffer newFileName = new StringBuffer(filename.substring(0, filename.lastIndexOf(".")));
				long time = new Date().getTime();
				filename = newFileName.append("-" + time).append("." + suffix).toString();
				File localUrl = new File(fileUrl+filename);
				// 获取文件要保存的目录地址
				File parentFile = localUrl.getParentFile();
				// 判断文件夹是否存在,不存在先创建
				if (!parentFile.exists()) {
					localUrl.mkdirs();
				}
				// 保存到本地磁盘
				file.transferTo(localUrl);
				
				String path = localUrl.getPath();
				PoiExcel excel = new PoiExcel(path,false);
				// 判断excel文件是否为空
				Workbook wb = excel.getWb();
				// 表索引从0开始
				Sheet sheetAt = wb.getSheetAt(0);
				if (sheetAt.getLastRowNum() <= 0) {
					Status status = new Status(410, "file_content Fail","excel内容不能空");
					result.put("status", status);
					return result;
				}
				//读取EXCEL到MAP,KEY 是SHEET NAME , VALUE是KEY对应SHEET的内容
				Map<Integer, List> sheetRules = new HashMap<Integer, List>();
				List columns = new ArrayList();
				columns.add(0);
				columns.add(1);
				columns.add(2);
				columns.add(3);
				columns.add(4);
				columns.add(5);
				columns.add(6);
				columns.add(7);
				columns.add(8);
				columns.add(9);
				columns.add(10);
				columns.add(11);
				columns.add(12);
				columns.add(13);
				columns.add(14);
				columns.add(15);
				columns.add(16);
				columns.add(17);
				columns.add(18);
				columns.add(19);
				// 第1个SHEET 提取的字段
				sheetRules.put(new Integer(0), columns); 
				Map<String, List> resultSet = excel.toArrayAtRange(sheetRules);
				ArrayList<HashMap<String, Object>> arrayList = new ArrayList<>();
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for(int i=0;i<resultSet.values().size();i++){
					System.err.println(resultSet.values());
				}
				for (List list : resultSet.values()) {
					if (list != null && list.size() > 0) {
						for (int i = 0; i < list.size(); i++) {
							if (i < 4) {
								continue;
							}
							HashMap<String, Object> map = new HashMap<>();
							List object = (List) list.get(i);
							if (object != null && object.size() > 0) {
								for (int j = 0; j < object.size(); j++) {
									map.put(j + "", object.get(j));
								}
							}
							if(!map.isEmpty()){
								map.put("infoId", "1");
				            	map.put("createdTime", sf.format(new Date()));
				            	map.put("userId", currentUser.getId());
				            	arrayList.add(map);
							}
						}
					}
				}
		try {
			rebuildService.saveListData(arrayList);
			result.put("status", Status.create(StatusMagic.OK));
		} catch (Exception e) {
		    e.printStackTrace();
			result.put("status", Status.create(StatusMagic.OPERATION_FAIL));
		}
		return result;
	    }
			
	}

2,导出

HashMap<String, Object> parameter = new HashMap<>();
				if (StringUtils.isNotBlank(county)) {
					parameter.put("county", county);
				} else {
					parameter.put("county", null);
				}
				
				List<HashMap<String, Object>> exportData = rebuildService.exportData(parameter);
				File file = new File(downloadUrl);
				if (!file.exists()) {
					file.mkdirs();// 创建文件夹
				}
				SystemUser currentUser = currentUser(SessionContext.getSession(request.getParameter("token")));
				//赋值文件模板
				String templatefile = request.getSession().getServletContext().getRealPath("")+"/resource/template/reconstruction.xlsx";
				File srcFile = new File(templatefile);
				Long time = new Date().getTime();
				File destFile = new File(downloadUrl+"/reconstruction-"+currentUser.getUsername()+"-"+time+".xlsx");
				FileUtils.copyFile(srcFile, destFile);
				
				PoiExcel poiExcel = new PoiExcel(destFile.getPath(), false);
				if (exportData != null && exportData.size() > 0) {
					poiExcel.populateSheet1("Sheet1", "A5", exportData, null);
				} else {
					poiExcel.setCellValue("Sheet0", "A5", "暂无数据");
				}
				poiExcel.submit();
				
				HttpHeaders headers = new HttpHeaders();
				String filename = destFile.getName();
				filename = new String(destFile.getName().getBytes("UTF-8"), "ISO8859-1"); // 设置字符编码为ISO8859-1
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				headers.setContentDispositionFormData("attachment", downloadUrl+filename); // 设置响应头中文件名称
				ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(
						FileUtil.readAsByteArray(destFile), headers,
						HttpStatus.CREATED);
                //返回文件流
				return responseEntity;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值