导入Excel 文件(https://www.cnblogs.com/smart-hwt/p/8243420.html)
1。js事件
function loadExcel(){
index = openDialogNoBtn(GetBasePath() + “/ipAdmin/loadnewview.do”,“导入Excel”, “380px”, “200px”, null,null);
}、
2. 控制器ipAdmin
@RequestMapping("/loadnewview")
public ModelAndView loadnewview() {
ModelAndView mv = new ModelAndView();
mv.setViewName(“Views/ip/loadExcel”);
return mv;
}
3。前台页面
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8”%>
4.控制器 /ipAdmin/loadExcel
@ResponseBody
@RequestMapping(value = “/loadExcel”, method = { RequestMethod.POST })
public Map<String, Object> loadExcel(@RequestParam(value=“file”,required = false) MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
Map<String, Object> map = new HashMap<String, Object>();
String result = importService.readExcelFile(file);
map.put(“message”, result);
return map;
}
5.Service 服务层
package com.sinnet.crm.service.ip;
import org.springframework.web.multipart.MultipartFile;
public interface ImportService {
/**
- 读取excel中的数据,生成list
*/
String readExcelFile(MultipartFile file);
}
6.ServiceImpl 实现层
package com.sinnet.crm.service.ip.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.poi.hssf.record.formula.functions.Count;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sinnet.crm.model.base.IManageUser;
import com.sinnet.crm.model.ip.BusinessIpParagraph;
import com.sinnet.crm.service.ip.ImportService;
import com.sinnet.crm.service.ip.IpAdminService;
import com.sinnet.crm.util.extension.ManageProvider;
import com.sinnet.crm.util.webService.ReadExcel;
@Service
public class ImportServiceImpl implements ImportService{
@Resource
public IpAdminService ipAdminService;
@Override
public String readExcelFile(MultipartFile file) {
String result = "";
//创建处理EXCEL的类
ReadExcel readExcel = new ReadExcel();
//解析excel,获取上传的事件单 验证EXCEL文件
List<Map<String, Object>> userList = readExcel.getExcelInfo(file);
//至此已经将excel中的数据转换到list里面了,接下来就可以操作list,可以进行保存到数据库,或者其他操作,
IManageUser users = null;
// ManageProvider.Instance().getCurent();
BusinessIpParagraph businessIpParagraph=new BusinessIpParagraph();
ArrayList<Object> arrayList = new ArrayList<>();
String loadfail = "";
for(Map<String, Object> user:userList){
loadfail = user.get("ipParagraph").toString();
businessIpParagraph.setUserId(user.get("userId").toString());
businessIpParagraph.setIpParagraph(user.get("ipParagraph").toString());
businessIpParagraph.setUseType(user.get("useType").toString());
businessIpParagraph.setComputerRoomId(user.get("computerRoomId").toString());
businessIpParagraph.setText4(user.get("description").toString());
businessIpParagraph.setSelect0(user.get("state").toString());
try {
users=ManageProvider.Instance().getCurent();
String count = ipAdminService.saveIpP(businessIpParagraph, users);
} catch (Exception e) {
arrayList.add(loadfail);
//没有通过的 ipParagraph
e.printStackTrace();
}
}
if(userList != null && !userList.isEmpty()){
result = "上传成功";
}else{
result = "上传失败";
}
if(arrayList!=null) {
result = arrayList+"未上传";
}
return result;
}
}
7.工具类 ReadExcel
package com.sinnet.crm.util.webService;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
public class ReadExcel {
// 总行数
private int totalRows = 0;
// 总条数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg;
// 构造方法
public ReadExcel() {
}
// 获取总行数
public int getTotalRows() {
return totalRows;
}
// 获取总列数
public int getTotalCells() {
return totalCells;
}
// 获取错误信息
public String getErrorInfo() {
return errorMsg;
}
/**
* 读EXCEL文件,获取信息集合
*
* @param fielName
* @return
*/
public List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
// 获取文件名
String fileName = mFile.getOriginalFilename();
// List<Map<String, Object>> userList = new LinkedList<Map<String, Object>>();
try {
// 验证文件名是否为Excel
if (!validateExcel(fileName)) {
return null;
}
boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
return createExcel(mFile.getInputStream(), isExcel2003);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据excel里面的内容读取信息
*
* @param is 输入流
* @param isExcel2003 excel是2003还是2007版本
* @return
* @throws IOException
*/
public List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
try {
Workbook wb = null;
if (isExcel2003) {
// 当excel是2003时,创建excel2003
wb = new HSSFWorkbook(is);
} else {
// 当excel是2007时,创建excel2007
wb = new XSSFWorkbook(is);
}
return readExcelValue(wb);// 读取Excel里面的信息
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 读取Excel里面的信息
*
* @param wb
* @return
*/
private List<Map<String, Object>> readExcelValue(Workbook wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
if (totalRows > 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
// 循环Excel行数
for (int r = 0; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
// 循环Excel的列
Map<String, Object> map = new HashMap<String, Object>();
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 1) {
row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
map.put("userId", cell.getStringCellValue());
} else if (c == 2) {
row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
map.put("ipParagraph",cell.getStringCellValue());
} else if (c == 3) {
row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
map.put("useType",cell.getStringCellValue());
}else if (c == 4) {
row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
map.put("computerRoomId",cell.getStringCellValue());
}else if (c == 5) {
row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
map.put("description",cell.getStringCellValue());
}else if (c == 6) {
row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
map.put("state",cell.getStringCellValue());
}else if (c == 7) {
row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
map.put("text5",cell.getStringCellValue());
}else if (c == 8) {
row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
map.put("text6",cell.getStringCellValue());
}
}
}
// 添加到list
userList.add(map);
}
return userList;
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
8.服务
public interface IpAdminService {
/**
* 添加
* @param bipP
* @param user
* @return
*/
public String saveIpP(BusinessIpParagraph bipP,IManageUser user) throws Exception;
}
9.IpAdminServiceImpl
@Override
public String saveIpP(BusinessIpParagraph bipP, IManageUser user) throws Exception{
bipP.setCreateUserId(user.getUserId());
if(StringUtils.isEmpty(bipP.getDeptId())){
bipP.setDeptId(user.getDepartmentId());
}
/封装请求参数/
Map<String,String> args = JSONHelper.toHashMap(JSONHelper.objectToJson(bipP));
JSONObject result = WebServiceHelper.requestByPost(“ip_service”, “IpParagraph”, “saveIpP”, args);
if(!“success”.equals(result.getString(“state”))){
throw new RuntimeException(result.getString(“message”));
}else{
return result.getString(“id”);
}
}