前端 excel文件上傳

<div id="setManager-store-upload" style="display:none">
						
<form id="uploadForm"> 
							
<div style="height:40px;padding-left:40px;">上傳文件:<input type="file" id="file" name="userUploadFile"></div>  
<div style="height:40px;padding-left:40px;"><input type="button" id="uploadFile" value="導入"><a href='#' style="" onclick="getTemplateStore()">下載模板</a></div>
</form>
<div id="store-list-upload" class="store-list">
</div>
</div>

 JS CODE:javascript

$("#uploadFile").click(function(){
$('#store-list-upload').empty();

var regionNo = $("#regionNo").find("option:selected").val();

if(regionNo === ""){
jQuery.messager.alert('提示','請選擇所在地區!','info');
return;
}

var brandStr = "";
$.each($("input[name=setBrand-data]"),function(){
if($(this).prop("checked")){
brandStr = brandStr + $(this).val() + "##";
}
});

if(brandStr === ""){
jQuery.messager.alert('提示','請選擇品牌權限!','info');
return;
}

var file = $("#file")[0].files[0];
if (!file) {
jQuery.messager.alert('提示','請選擇需導入的文件!','info');
return;
}

var formdata = new FormData();
formdata.append("regionNo", regionNo);
formdata.append("brandNos", brandStr);
formdata.append("sourceFile", file);
$.ajax({
url:'/admin/NormalManager/uploadStore',
data: formdata,
type:'post',
// contentType: 'multipart/form-data',
processData: false,
contentType: false,
success:function(data){
if(data.ret === "1"){
jQuery.messager.alert('提示','導入成功!導入'+ data.data.length+"條數據",'info');
freshData(data.data);
}else if(data.ret === "0"){
jQuery.messager.alert('提示','導入失敗!數據有誤,請檢查導入的數據','info');
}
}
});
});

 

SPRING XML配置html

    <!-- 上傳下載 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="1000000"/>  
    </bean>前端

 

JAVA CODE: CONTROLLERjava

@RequestMapping(value = "/uploadStore", method = RequestMethod.POST)
	@ResponseBody
	public Object uploadCSV(NormalManagerVO vo, @RequestParam("sourceFile") MultipartFile sourceFile,
			@RequestParam("brandNos") String brandNos, @RequestParam("regionNo") String regionNo, 
			HttpServletRequest request, HttpServletResponse response) {

		try {
			
			// 判斷文件是否爲空
			if (sourceFile == null)
				return ResultUtil.fail();
			
			// 判斷所屬地區是否爲空
			if (StringUtils.isEmpty(regionNo))
				return ResultUtil.fail();
			
			// 判斷品牌權限是否爲空
			if (StringUtils.isEmpty(brandNos))
				return ResultUtil.fail();
			
			
			// 獲取文件名
			String name = sourceFile.getOriginalFilename();
			// 進一步判斷文件是否爲空(即判斷其大小是否爲0或其名稱是否爲null)
			long size = sourceFile.getSize();
			if (name == null || ("").equals(name) && size == 0)
				return ResultUtil.fail();
	
			// 批量導入。參數:文件名,文件。
			//建立處理EXCEL
			ExcelUtils readExcel = new ExcelUtils();
			readExcel.setMaxRows(3);
			
			// 解析excel,獲取客戶信息集合。
			List<Map<String, Object>> listModel = readExcel.getExcelInfo(name, sourceFile);

			if (listModel == null || listModel.isEmpty()) {
				return ResultUtil.fail();
			}
			
			// 處理數據
			List<String> listBrand  = Arrays.asList(brandNos.split("##"));
			
			Set<String> setStore = new HashSet<>();
			for (Map<String, Object> temp : listModel) {
				if (!listBrand.contains(temp.get("brandNo"))) {
					return ResultUtil.fail();
				} 
				setStore.add((String) temp.get("storeNo"));
			}
			
			// 獲取數據
			Map<String,Object> params = Maps.newHashMap();
			params.put("regionNo", regionNo);
			params.put("brandNoList", listBrand);
			params.put("storeList", setStore);
			List<Map<String, String>> listRes = normalManager.getStoreListByParams(params);
			
			// 判斷查詢出來的店鋪個數是否同導入的店鋪個數相同
			if (listRes.isEmpty() || listRes.size()!= setStore.size()){
				return ResultUtil.fail();
			}
			
			// 給前端添加選中標示
			for(Map<String,String> kv : listRes){
				kv.put(AdminUtil.SELECT, "1");
			}
			
			return ResultUtil.success(listRes, listRes.size());
		} catch (Exception e) {
			logger.error("導入失敗", e);
			return ResultUtil.fail();
		}
	}

 

package com.jn.iexcel.web.utils;

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.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;

/**
 * excel200三、2007 文件通用解析工具類
 * @author sun.xh
 * @date 2018.9.10
 */
public class ExcelUtils {

	// 總行數
	private int totalRows = 0;
	// 總條數
	private int totalCells = 0;
	// 錯誤信息接收器
	private String errorMsg;
	
	// 最多行數
	private int maxRows;

	// 構造方法
	public ExcelUtils() {
	}

	// 獲取總行數
	public int getTotalRows() {
		return totalRows;
	}

	// 獲取總列數
	public int getTotalCells() {
		return totalCells;
	}

	// 獲取錯誤信息
	public String getErrorInfo() {
		return errorMsg;
	}

	public int getMaxRows() {
		return maxRows;
	}

	public void setMaxRows(int maxRows) {
		this.maxRows = maxRows;
	}

	/**
	 * 驗證EXCEL文件
	 * 
	 * @param filePath
	 * @return
	 */
	public boolean validateExcel(String filePath) {
		if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))) {
			errorMsg = "文件名不是excel格式";
			return false;
		}
		return true;
	}

	/**
	 * 讀EXCEL文件,獲取客戶信息集合
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> getExcelInfo(String fileName, MultipartFile Mfile) {

		// 把spring文件上傳的MultipartFile轉換成CommonsMultipartFile類型
//		CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; // 獲取本地存儲路徑
//		File file = new File("D:\\fileupload");
//		// 建立一個目錄 (它的路徑名由當前 File 對象指定,包括任一必須的父路徑。)
//		if (!file.exists())
//			file.mkdirs();
		// 新建一個文件
//		File file1 = new File("D:\\fileupload" + new Date().getTime() + ".xlsx");
		// 將上傳的文件寫入新建的文件中
//		try {
//			cf.getFileItem().write(file1);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		// 初始化客戶信息的集合
		List<Map<String, Object>> customerList = new ArrayList<>();
		// 初始化輸入流
		InputStream is = null;
		try {
			// 驗證文件名是否合格
			if (!validateExcel(fileName)) {
				return null;
			}
			// 根據文件名判斷文件是2003版本仍是2007版本
			boolean isExcel2003 = true;
			if (WDWUtil.isExcel2007(fileName)) {
				isExcel2003 = false;
			}
			// 根據新建的文件實例化輸入流
			is = Mfile.getInputStream();
			// 根據excel裏面的內容讀取客戶信息
			customerList = getExcelInfo(is, isExcel2003);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					is = null;
					e.printStackTrace();
				}
			}
		}
		return customerList;
	}

	/**
	 * 根據excel裏面的內容讀取客戶信息
	 * 
	 * @param is
	 *            輸入流
	 * @param isExcel2003
	 *            excel是2003仍是2007版本
	 * @return
	 * @throws IOException
	 */
	public List<Map<String, Object>> getExcelInfo(InputStream is, boolean isExcel2003) {
		List<Map<String, Object>> customerList = null;
		try {
			/** 根據版本選擇建立Workbook的方式 */
			Workbook wb = null;
			// 當excel是2003時
			if (isExcel2003) {
				wb = new HSSFWorkbook(is);
			} else {// 當excel是2007時
				wb = new XSSFWorkbook(is);
			}
			// 讀取Excel裏面客戶的信息
			customerList = readExcelValue(wb);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return customerList;
	}

	/**
	 * 讀取Excel裏面客戶的信息
	 * 
	 * @param wb
	 * @return
	 */
	private List<Map<String, Object>> readExcelValue(Workbook wb) {
		// 獲得第一個shell
		Sheet sheet = wb.getSheetAt(0);

		// 獲得Excel的行數
		this.totalRows = sheet.getPhysicalNumberOfRows();
		
		// 不能超過最大限制
		if ((totalRows - 1) > maxRows) {
			return new ArrayList<>();
		}

		// 獲得Excel的列數(前提是有行數)
		if (totalRows >= 1 && sheet.getRow(0) != null) {
			this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
		}

		List<Map<String, Object>> listModel = new ArrayList<>();
		Map<String, Object> mapTemp;
		
		// 循環Excel行數,從第二行開始。標題不入庫
		for (int r = 1; r < totalRows; r++) {
			Row row = sheet.getRow(r);
			if (row == null)
				continue;
			mapTemp = new HashMap<>();
			try {
				Thread.currentThread().sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			// 循環Excel的列
			for (int c = 0; c < this.totalCells; c++) {
				Cell cell = row.getCell(c);
				if (null != cell) {
					if (c == 0) {
						mapTemp.put("brandNo", cell.getStringCellValue());// 品牌部
					} else if (c == 1) {
						mapTemp.put("storeNo", cell.getStringCellValue());// 店鋪編碼
					} else if (c == 2) {
						mapTemp.put("storeName", cell.getStringCellValue());// 店鋪名稱
					}
				}
			}
			// 添加店鋪
			listModel.add(mapTemp);
		}
		return listModel;
	}

}

 

package com.jn.iexcel.web.utils;

/**
 * 校驗是否爲excel200三、2007 工具類
 * @author sun.xh
 * @date 2018.9.10
 */
public class WDWUtil {
	
	/**
	 * 是不是2003的excel,返回true是2003
	 * @param filePath
	 * @return
	 */
	public static boolean isExcel2003(String filePath) { 
		return filePath.matches("^.+\\.(?i)(xls)$"); 
	}
	 
	/**
	 * 是不是2007的excel,返回true是2007
	 * @param filePath
	 * @return
	 */
	public static boolean isExcel2007(String filePath) {
		return filePath.matches("^.+\\.(?i)(xlsx)$");
	}
}
相關文章
相關標籤/搜索