1. 程式人生 > >SpringMVC操作Excel上傳下載

SpringMVC操作Excel上傳下載

依賴jar包

maven工程可以直接將下面兩個依賴拿走,不謝!

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.0</version> </dependency>

編寫操作excel的工具類

public class ExcelUtil {

	private static final String XLS = ".xls";
	private static final String XLSX = ".xlsx";
	
	/**
	 * 
	 * 讀取excel檔案轉化為List<Map<String, Object>>集合
	 * 
	 * @param suffix 檔案字尾
	 * @param is 檔案轉化的輸入流
	 * @return List<Map<String, Object>>
	 */
public static List<Map<String, Object>> readExcel(String suffix, InputStream is) { try { // 判斷後綴名和輸入流是否為空 if(suffix == null || "".equals(suffix) || is == null) { return null; } // 建立excel物件 Workbook book = null; if(XLS.equals(suffix)) { book = new HSSFWorkbook
(is); } else if (XLSX.equals(suffix)) { book = new XSSFWorkbook(is); } // 建立返回值集合 List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); // 獲取第一個sheet物件 Sheet sheet = book.getSheetAt(0); // 獲取最後一行的行號 int lastRowNum = sheet.getLastRowNum(); // 標題陣列 String[] titles = null; // 迴圈獲取行 for(int i = 0; i <= lastRowNum; i++) { // 獲取行物件 Row row = sheet.getRow(i); Map<String, Object> map = new HashMap<String, Object>(); // 獲取最後一列列號 int lastCellNum = row.getLastCellNum(); // 迴圈獲取列 for(int j = 0; j < lastCellNum; j++) { // 單元格物件 Cell cell = row.getCell(j); // 單元格資料 String val = cell.getStringCellValue(); // 標題 if(i == 0) { if(titles == null) { titles = new String[lastCellNum]; } // 標題存放到標題陣列 titles[j] = val; } // 資料 map.put(titles[j], val); } // 標題行跳過,不作為資料 if(i == 0) { continue; } // 將資料存入集合 list.add(map); } return list; } catch (Exception e) { e.printStackTrace(); return null; } } /** * * @param sheetName sheet名 * @param suffix 字尾名 * @param dataList 資料集合 * @return Workbook */ public static Workbook createExcel(String sheetName, String suffix, List<Map<String, Object>> dataList) { // 判斷基本引數 if(sheetName == null || "".equals(sheetName) || suffix == null || "".equals(suffix) || dataList == null || dataList.size() == 0) { return null; } // 建立excel物件 Workbook book = null; if(XLS.equals(suffix)) { book = new HSSFWorkbook(); } else if (XLSX.equals(suffix)) { book = new XSSFWorkbook(); } // 建立sheet Sheet sheet = book.createSheet(sheetName); int r = 0; for(int i = 0; i < dataList.size(); ) { // 資料 Map<String, Object> data = dataList.get(i); // 建立行 Row row = sheet.createRow(r); Set<String> titles = data.keySet(); int j = 0; for(String title : titles) { // 建立單元格 Cell cell = row.createCell(j++); // 給單元格賦值 if(r == 0) { cell.setCellValue(title); } else { cell.setCellValue(data.get(title) + ""); } } if(r != 0) { i++; } r++; } return book; } }

在springMVC配置檔案中配置上傳檔案所需要的解析器

<!-- 檔案上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 上傳檔案的編碼格式 -->
	<property name="defaultEncoding" value="UTF-8"/>
	<!-- 
		設定上傳檔案的大小 單位是位元組數
		-1代表不限制上傳檔案大小
	-->
	<property name="maxUploadSize" value="-1"/>
</bean>

編寫controller

上傳檔案時必須在方法的引數中新增【MultipartFile】

	@RequestMapping(value="/import", method= {RequestMethod.POST})
	public void importExcel(MultipartFile file) throws Exception {
		// 檔名
		String filename = file.getOriginalFilename();
		// 字尾名
		String suffix = filename.substring(filename.lastIndexOf("."));
		// 輸入流
		InputStream is = file.getInputStream();
		// 讀excel
		List<Map<String, Object>> list = ExcelUtil.readExcel(suffix, is);
		System.out.println(list);
	}
	
	@RequestMapping(value="/export", method= {RequestMethod.GET, RequestMethod.POST})
	public void exportExcel(HttpServletResponse response) throws Exception {
		// 檔名
		String filename = "userInf";
		// 字尾名
		String suffix = ".xlsx";
		// sheetName
		String sheetName = "userInfo";
		
		List<Map<String, Object>> list = studentService.queryForList(null);
		// 讀excel
		Workbook excel = ExcelUtil.createExcel(sheetName, suffix, list);
		
		// OutputStream out = new FileOutputStream(new File("D://"+ filename + suffix));
		response.setHeader("content-disposition", "attachment;filename=" + filename + suffix);
		ServletOutputStream out = response.getOutputStream();
		excel.write(out);
		out.flush();
		out.close();
	}

jsp頁面

上傳檔案時要求form表單中
    必須新增屬性【enctype=“multipart/form-data”】
    提交方式必須是【method=“post”】

<form action="stuC/import" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" value="匯入">
</form>

測試

瀏覽器輸入地址開始測試
資料庫資料:
在這裡插入圖片描述
excel效果(這裡沒有做顏色等設定,有點蒼白)
在這裡插入圖片描述


個人愚見:

一個人有一千種操作excel的習慣,變數太多,不可能面面俱到,所以工具類編寫過程也是指定規則的過程。想用我的功能就必須按照我的規矩來,否則分分鐘讓你享受藍屏的刺激。
所以要求excel的單元格格式必須設定為文字型別,需要時可以在插入資料庫時做轉換即可。

以上內容純屬個人愚見,如有問題,請不吝賜教!!