1. 程式人生 > >Java上傳Excel檔案匯入資料

Java上傳Excel檔案匯入資料

Controller中接收form表單提交的檔案域:

public Map importConsumer(@RequestParam("file") MultipartFile file)

讀取Excel工具類 這裡我以Consumer實體類來寫,大家可以自行封裝:

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 filePath
	 * @return
	 */
	public boolean validateExcel(String filePath)
	{
		if(filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath)))
		{
			errorMsg = "檔名不是excel格式";
			return false;
		}
		return true;
	}

	/**
	 * 讀EXCEL檔案,獲取客戶資訊集合
	 * 
	 * @param fielName
	 * @return
	 */
	public List<Consumer> 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<Consumer> customerList = new ArrayList<Consumer>();
		// 初始化輸入流
		InputStream is = null;
		try
		{
			// 驗證檔名是否合格
			if(!validateExcel(fileName))
			{
				return null;
			}
			// 根據檔名判斷檔案是2003版本還是2007版本
			boolean isExcel2003 = true;
			if(WDWUtil.isExcel2007(fileName))
			{
				isExcel2003 = false;
			}
			// 根據新建的檔案例項化輸入流
			is = new FileInputStream(file1);
			// 根據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<Consumer> getExcelInfo(InputStream is, boolean isExcel2003)
	{
		List<Consumer> 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<Consumer> 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<Consumer> customerList=new ArrayList<Consumer>();
	       Consumer consumer;            
	      //迴圈Excel行數,從第二行開始。標題不入庫
	       for(int r=1;r<totalRows;r++){
	           Row row = sheet.getRow(r);
	           if (row == null) continue;
	           consumer = new Consumer();
	           
	           //迴圈Excel的列
	           for(int c = 0; c <this.totalCells; c++){    
	               Cell cell = row.getCell(c);
	               cell.setCellType(CellType.STRING);
	               if(null != cell)
					{
						if(c == 0)
						{
							consumer.setName(cell.getStringCellValue()); 		// 姓名
						}
						else if(c == 1)
						{
							consumer.setPhone(cell.getStringCellValue()); 		// 手機號碼
						}
						else if(c == 2)
						{
							consumer.setEmail(cell.getStringCellValue()); 		// 客戶簡稱
						}
						else if(c == 3)
						{
							consumer.setCreateUserId(cell.getStringCellValue());	//所屬訪員賬號
						}
					}
	           }
	           //新增客戶
	           customerList.add(consumer);
	       }
	       return customerList;
	  }
}
Service裡面呼叫:
public Map importConsumer(MultipartFile file,Users currentUser)
	{
		Map<String, Object> map = new HashMap<String, Object>();
		
		boolean b = false;
		// 建立處理EXCEL
		ReadExcel readExcel = new ReadExcel();
		// 解析excel,獲取客戶資訊集合。
		List<Consumer> ConsumerList = readExcel.getExcelInfo(file.getOriginalFilename(), file);

		if(ConsumerList != null)
		{
			b = true;
			map.put("code", 0);
		}
		else
		{
			map.put("code", -1);
		}
		map.put("msg", "");
		
		for(Consumer consumer:ConsumerList)
		{
			String guid = java.util.UUID.randomUUID().toString();
			consumer.setId(guid);
			consumer.setCompanyId(currentUser.getCompanyId());
			consumer.setCreateTime(formatter.format(new Date()));
			consumerDao.insert(consumer);  //或者進行批量儲存
		}
		return map;
	}

注意會出現異常:java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap

這是缺少jar包,需要下載commons-collections4-4.1.jar,然後放在lib下面,build path 加入到專案裡面去.

cell.getStringCellValue()
這句程式碼也可能報異常,獲取單元格的資料都為String型別,單元格的資料還可能是其他型別資料,

迴圈excel列需要設定一下都轉成String型別,row.getCell(0).setCellType(CellType.STRING);

基礎程式碼,大家需要自行擴充套件。