首先按照要求的模板制作Excel文档,然后上传之服务器,并读入到数据库中
本文章针对,先将Excel文档存在服务器中,然后再将存放文档的路径传到Service层,最后写入到数据库当中,具体看一下代码:
前端代码:
导入员工
<#include "/common/global_css.ftl">
根据请求路径映射到后端的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 staffList = staffMapper.selectAll(staff.getPartnerId());
boolean isExistJob = false;
boolean isExistStaff = false;
for(int z=0;z 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 = 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 "导入错误,请联系管理员!";
}
}
}
}