1. 程式人生 > >Excel資料匯入到資料庫

Excel資料匯入到資料庫

一、前臺請求

 二、後臺邏輯


import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.ss.usermodel.WorkbookFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 匯入excel
 * 
 * @author Administrator
 *
 */
public class ExcelImport {

	/**
	 * 匯入excel 說明 每行每列都是從0開始 返回值 isSuccess == true 時帶回表格的所有資料、最大行數和最大列數
	 * 
	 * @param file
	 * @param minRow
	 * @param redirectAttributes
	 * @return
	 */
	public static Map<String, Object> importStuParentList(HttpServletRequest request, int minRow) {
		Map<String, Object> map = new HashMap<>();
		map.put("isSuccess", false);
		// 建立表格
		try {
			MultipartHttpServletRequest multipartFile = (MultipartHttpServletRequest) request;

			MultipartFile file = multipartFile.getFile("file");
			Workbook workbook = WorkbookFactory.create(file.getInputStream());
			Sheet sheet = workbook.getSheetAt(0);
			// 獲取最大行數
			int totalRows = sheet.getLastRowNum();
			if (totalRows <= minRow - 1) {
				map.put("msg", "沒有資料");
				return map;
			}
			// 獲取最大列數
			int totalCells = 0;
			if (totalRows > 0 && sheet.getRow(0) != null) {
				totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
			}
			// 讀取資料放入集合
			for (int i = minRow + 1; i <= totalRows; i++) {
				//獲取每行
				Row row = sheet.getRow(i);
				for (int j = 0; j < totalCells; j++) {
					//獲取每行中的每個單元格的資料
					Cell cell = row.getCell(j);
					
					//把資料存入到資料庫
					
				}
			}
			map.put("isSuccess", true);
			map.put("sheet", sheet);
			map.put("totalRows", totalRows);
			map.put("totalCells", totalCells);
			return map;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			map.put("msg", "資訊有誤");
		}
		return map;
	}

}