Excel文件的上传和读取

首先按照要求的模板制作Excel文档,然后上传之服务器,并读入到数据库中

本文章针对,先将Excel文档存在服务器中,然后再将存放文档的路径传到Service层,最后写入到数据库当中,具体看一下代码:

前端代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>导入员工</title>
	<#include "/common/global_css.ftl">
	<link href="${request.getContextPath()}/css/validform/style.css" rel="stylesheet" type="text/css" media="all"/>
	<link href="${request.getContextPath()}/css/jbox/jbox_blue.css" rel="stylesheet" type="text/css" id="jbox"/>
	<link href="${request.getContextPath()}/css/datatable/datatable.css" rel="stylesheet" type="text/css"/>
	<link href="${request.getContextPath()}/css/chosen/chosen.css" rel="stylesheet" type="text/css"/>
	<style type="text/css">

	</style>
</head>
<body>
	<div class="form">
		<form class="addForm" target="_parent" id="userInfoFromExcelAddForm" action="${request.getContextPath()}/staff/staff/importStaff" method="post">
			<input type="hidden" id="pageContext" value="${request.getContextPath()}" />
			<input type="hidden" name="partnerId" value="${Session.partnerId}" />
			<table border="0" cellspacing="0" cellpadding="0" width="100%" style="margin-top:80px;" class="boxTable boxmar">
		            <tr align="center">
		            	<td align="right" style="width:80px"><span class="check"></span>文件上传:</td>
		            	<td style="width:150px">
	                   		 <input type="hidden" name="importExceForBath" id="importExceForBath" value="" /> 
							  <input type="file" name="photo" id="photo" style="margin-left: 100px;">
							  <input type="button" id="ts" class="btn" value="上传" onclick="uploadPhotos()">	
		            	</td>
		            </tr>
	             <tr align="center">
    				<td colspan="2">
    					<input class="btn" type="button" id="saveBtn" value="保存">
    					<input type="button" class="btn dis cancel" id="cancelBtn" value="取消">
    				</td>
  				</tr>
	  		</table>
		</form>
	</div>
	<script type="text/javascript" src="${request.getContextPath()}/js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/allPage.js" contextPath="${request.getContextPath()}"  id="allPageJs"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/validform/Validform_v5.3.2.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/datatable/jquery.dataTables.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox.src.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/jbox/jquery.jBox-zh-CN.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/rbcList.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/strUtils/dateUtil.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/utils/chosen/chosen.jquery.min.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/my97date/WdatePicker.js"></script>
	<script type="text/javascript" src="${request.getContextPath()}/js/modules/ques/add_question.js"></script>
	
	<script type="text/javascript">
	
	//文件上传
		 function uploadPhotos(){ 
		     var myFormData = new FormData();
		     myFormData.append('photos',$('#photo')[0].files[0]);
		     var targetUrl = '${request.getContextPath()}/staff/staff/saveFile';
				$.ajax({
		            type:"post",
		            url:targetUrl,
		            data:myFormData,
		            cache: false,
		            async:false,
		            processData: false,
	                contentType: false,
		            success:function(data) {
			    		var result = data;
						console.log(data)
			    		if(data!="false"){
			    		 $("#ts").val("上传成功!");
			    		}
			    		 $("#importExceForBath").val(data);
			    	}
			    });
		 }
	
		$(function(){
			$("#saveBtn").click(function(){
				var importExceForBath=$("#importExceForBath").val();
				if(importExceForBath==''|| importExceForBath==null){
					$.jBox.tip("请上传文件!","warnning");
					return false;
				}
				$("#userInfoFromExcelAddForm").submit();
				window.parent.load();
			});
			
			$('#cancelBtn').click(function(){
			});
		});
		
			$('.chosen').chosen({
				"no_results_text":'未找到匹配数据!',
				"width":"160px",
				"allow_single_deselect":true
			});
	</script>
</body>
</html>

根据请求路径映射到后端的Controller层:

package com.nuocai.modules.staff.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse.DeptGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse.ListUserResponse;
import com.nuocai.core.base.pojo.PageParameter;
import com.nuocai.core.base.pojo.Pagination;
import com.nuocai.core.common.utils.upload.FileUploadConstants;
import com.nuocai.core.mybase.CommonDto;
import com.nuocai.core.mybase.Constants.IS_VALID;
import com.nuocai.core.mybase.MyBaseController;

import com.nuocai.modules.staff.model.Department;
import com.nuocai.modules.staff.model.Post;
import com.nuocai.modules.staff.model.Staff;
import com.nuocai.modules.staff.model.WCUser;
import com.nuocai.modules.staff.model.WCdepartment;
import com.nuocai.modules.staff.service.DepartmentService;
import com.nuocai.modules.staff.service.PostService;
import com.nuocai.modules.staff.service.StaffService;
import com.nuocai.modules.partner.model.Partner;
import com.nuocai.modules.partner.service.PartnerService;
import com.nuocai.modules.staff.util.HandlEmployeeInformation;
import com.nuocai.modules.staff.util.getDingTalkInfo;
import com.nuocai.modules.staff.util.getEnterpriseWeChatInfo;

import jxl.Workbook;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Alignment;
import jxl.write.Border;
import jxl.write.Label;
import jxl.write.VerticalAlignment;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * Staff()管理 autogenerate V1.0 by edu-edu
 */
@Controller
@RequestMapping("/staff/staff")
public class StaffController extends MyBaseController {	
private static String getSavePath(String proVal) {

		if (proVal != null && proVal.equals("")) {
			proVal = "";
		}
		String saveFilePath = FileUploadConstants.getPropValue(proVal);
		if (saveFilePath == null || saveFilePath.equals("")) {
			return null;
		}
		if (!saveFilePath.endsWith("/"))
			saveFilePath += "/";
		// 生成文件保存路径
		File aSaveFile = new File(saveFilePath);
		if (!aSaveFile.isDirectory())
			aSaveFile.mkdirs();
		return saveFilePath;
	}

	/**
	 * UUID命名
	 *
	 */
	public static String reFileNameByUUID(String filePath, String fileName) {
		String uFileName = UUID.randomUUID().toString();
		uFileName = uFileName.substring(0, 8) + uFileName.substring(9, 13) + uFileName.substring(14, 18)
				+ uFileName.substring(19, 23) + uFileName.substring(24);
		int p = fileName.lastIndexOf(".");
		fileName = uFileName + fileName.substring(p, fileName.length());
		File file = new File(filePath + fileName);
		if (file.exists()) {
			fileName = reFileNameByUUID(filePath, fileName);
		}
		return fileName;
	}

	@SuppressWarnings("unused")
	@RequestMapping(value = { "/saveFile" }, method = RequestMethod.POST)
	@ResponseBody
	public String doGet(@RequestParam("photos") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String savePath = getSavePath("FILE_PATH_EXCEL");
		String path = savePath;// 文件路径
		double fileSize = file.getSize();
		byte[] sizebyte = file.getBytes();
		if (file != null) {// 判断上传的文件是否为空
			String type = null;// 文件类型
			String fileName = file.getOriginalFilename();// 文件原名称
			fileName = reFileNameByUUID(savePath, fileName);
			// 判断文件类型
			type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())
					: null;
			if (type != null) {// 判断文件类型是否为空
				if ("XLS".equals(type.toUpperCase()) || "XLSX".equals(type.toUpperCase())) {
					// 项目在容器中实际发布运行的根路径
					String realPath = request.getSession().getServletContext().getRealPath("/");
					// 自定义的文件名称
					String trueFileName = String.valueOf(System.currentTimeMillis()) + "." + type;
					// 设置存放excel文件的路径
					path = savePath + fileName;
					// 转存文件到指定的路径
					file.transferTo(new File(path));
					request.getSession().setAttribute("trueFileName", fileName);
					return fileName;
				}
			} else {
				return "false";
			}
		} else {
			return "false";
		}
		return "false";
	}
    	/** 导入数据 */
	@RequestMapping(value = "/importStaff", method = RequestMethod.POST)
	public String importStaff(@ModelAttribute("staff") Staff staff, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		Long partnerId = (Long) request.getSession().getAttribute("partnerId");
		// 企业信息
		Partner partner = partnerService.load(partnerId);

		if (partner.getSyncMethod() == 0) {
			partner.setSyncMethod(1);
			partnerService.update(partner);
		}

		if (partner.getSyncMethod() != 1) {
			redirectAttributes.addFlashAttribute("message",
					"已经使用" + HandlEmployeeInformation.SYNCHMETHOD[partner.getSyncMethod()]);

		} else {
			String trueFileName = (String) request.getSession().getAttribute("trueFileName");
			// 添加业务逻辑——导入数据
			staff.setIsValid(IS_VALID.YES.getValue());
			staff.setCreateDate(new Date());
			staff.setCreateUser(this.getCurrentUser().getId());
			String result = staffService.importExcelData(staff, trueFileName);
			if ("1".equals(result)) {
				redirectAttributes.addFlashAttribute("message", "导入成功");
			} else {
				redirectAttributes.addFlashAttribute("message", "导入失败");
			}
		}
		return "redirect:/staff/staff/";
	}
}
//以下是需要用到的工具类
package com.nuocai.core.common.utils.upload;
import java.io.InputStream;
import java.util.Properties;

public class FileUploadConstants {
	public static String EXCELPATH_USER = "";
	
	private static Properties prop=null;
	
	static{
		String path="/config/fileUploadSavePath_windows.properties";
		if(isLinux()){
			path="/config/fileUploadSavePath_linux.properties";
		}
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				EXCELPATH_USER=prop.getProperty("EXCELPATH_USER");
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	public static String getPropValue(String key){
		String path="/config/fileupload/fileUploadSavePath_windows.properties";
		String val = null;
		if(isLinux()){
			path="/config/fileupload/fileUploadSavePath_linux.properties";
		}
		InputStream in=FileUploadConstants.class.getResourceAsStream(path);
		if(in!=null){
			prop=new Properties();
			try {
				prop.load(in);
				val = prop.getProperty(key);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	
	public  static boolean isLinux(){
		String osType = System.getProperties().getProperty("os.name").toLowerCase();
		if(osType.startsWith("windows")){
			return false;
		}
		else{
			return true;
		}
	}
}

对于不足的代码和不理解的地方,可观看本博主第一篇博文

最后,就是调用Service层中的具体方法去取出文件并读取出来保存到数据库当中:

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 20)
	public String importExcelData(Staff staff, String trueFileName) {
		InputStream is = null;
		Long partnerId = staff.getPartnerId();
		try {
			// is = new FileInputStream(userInfoFromExcel.getImportExceForBath());
			String fileUrl = FileUploadConstants.getPropValue("FILE_PATH_EXCEL") + "/" + trueFileName;
			System.out.println("===========>fileUrl:" + fileUrl);
			FileInputStream fileInputStream = new FileInputStream(fileUrl);
		    BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		    POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
		    HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
		    HSSFSheet sheet = workbook.getSheet("员工导入模板");
		    int lastRowIndex = sheet.getLastRowNum();
		    int j;
		    for (int i = 1; i <= lastRowIndex; i++) {
		    	Staff staff1 = new Staff();
		    	staff1.setPartnerId(partnerId);
		        HSSFRow row = sheet.getRow(i);
		        if (row == null) { break; }
		        j = 0 ;
		        	row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
		            String cellValue = row.getCell(j).getStringCellValue();
		            staff1.setJobNumber(cellValue);
		            staff1.setStaffName(row.getCell(j+1).getStringCellValue());
		            List<Staff> staffList = staffMapper.selectAll(staff.getPartnerId());
		            boolean isExistJob = false;
		            boolean isExistStaff = false;
		            for(int z=0;z<staffList.size();z++) {
		            	isExistJob=(staffList.get(z).getJobNumber().equals(cellValue));
		            	isExistStaff=(staffList.get(z).getStaffName().equals(row.getCell(j+1).getStringCellValue()));
		            	if(isExistJob && isExistStaff) {
		            		break;
		            	}
		            }
		            if(isExistJob&&isExistStaff) {
		            	continue;
		            }
		            if (row.getCell(j+2).getStringCellValue().equals("男")) {
						staff1.setGender(1);
					} else {
						staff1.setGender(0);
					}
		            List<Department> dept = departmentMapper.selectAll(staff.getPartnerId());
					for (int z = 0; z < dept.size(); z++) {
						if (row.getCell(j+3).getStringCellValue().equals(dept.get(z).getDepartmentName())) {
							staff1.setDepartmentId(dept.get(z).getId());
						}
					}
					List<Post> post = postMapper.selectAll(staff.getPartnerId());
					for (int z = 0; z < post.size(); z++) {
						if (row.getCell(j+4).getStringCellValue().equals(post.get(z).getPostName())) {
							staff1.setPostId(post.get(z).getId());
						}
					}
					staff1.setCreateDate(new Date());
					staff1.setIsValid(IS_VALID.YES.getValue());
					staff1.setCreateUser(staff.getId());
		            staffMapper.insert(staff1);
		        }
		    bufferedInputStream.close();
		    return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "导入失败,请联系管理员!";
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
					return "导入错误,请联系管理员!";
				}
			}
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值