1. 程式人生 > >SSM框架poi匯入匯出Excel(MySQL)

SSM框架poi匯入匯出Excel(MySQL)

Excel匯入的MySQL的方法:

瀏覽器選擇excel檔案,傳至服務端,在服務端解析此excel並將資料匯入到資料庫中。

原始碼下載

這裡只儲存關鍵程式碼,詳細的原始碼可點選上面原始碼下載前往下載

1,專案結構:

2,匯入頁面:

jsp:

<table>
	<tr>
	    <td><input type="file" id="upload" name="upload" value="" /></td>
	    <td><button onclick="uploadFile()">上傳</button></td>
	    <td><button onclick="OutputExce()">匯出</button></td>
	</tr>
</table>


js:

function uploadFile() {
			var file = $("#upload").val();
			file = file.substring(file.lastIndexOf('.'), file.length);
			if (file == '') {
				alert("上傳檔案不能為空!");
			} else if (file != '.xlsx' && file != '.xls') {
				alert("請選擇正確的excel型別檔案!");
			} else {
				ajaxFileUpload();
			}
		}
		function ajaxFileUpload() {

			var formData = new FormData();
			var name = $("#upload").val();
			formData.append("file", $("#upload")[0].files[0]);
			formData.append("name", name);
			$.ajax({
				url : "excel/InputExcel.do",
				type : "POST",
				async : false,
				data : formData,
				processData : false,
				contentType : false,
				beforeSend : function() {
					console.log("正在進行,請稍候");
				},
				success : function(e) {
					if (e == "01") {
						alert("匯入成功");
					} else {
						alert("匯入失敗");
					}
				}
			});
		}

		function OutputExce() {
			window.location.href = "/ExcelDemo/excel/OutputExcel.do";
		}

3,服務端解析處理Excel檔案:

Controller:

@RequestMapping(value = "/InputExcel.do")
	@ResponseBody
	public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
		String flag = "02";// 上傳標誌
		if (!file.isEmpty()) {
			try {
				String originalFilename = file.getOriginalFilename();// 原檔名字
				log.info("檔名:" + originalFilename);
				InputStream is = file.getInputStream();// 獲取輸入流
				flag = excelService.InputExcel(is, originalFilename);
			} catch (Exception e) {
				flag = "03";// 上傳出錯
				e.printStackTrace();
			}
		}
		return flag;
	}
	
	@RequestMapping(value = "/OutputExcel.do", produces = "application/form-data; charset=utf-8")
	@ResponseBody
	public String OutputExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html,charset=utf-8");

		List<EmpT> list = excelService.OutputExcel();

		String message = OutputExcel.OutExcel(request, response, list);
		if (message.equals("fail")) {
			ServletOutputStream out = response.getOutputStream();
			message = "匯出失敗,請重試";
			String s = "<!DOCTYPE HTML><html><head><script>alert('" + message + "');</script></head><body></body></html>";
			out.print(s);
		}
		return null;
	}

service:

        @Override
	public String InputExcel(InputStream is, String originalFilename) {
		Map<String,Object> ginsengMap = new HashMap<String,Object>();
		List<ArrayList<Object>> list;
		if (originalFilename.endsWith(".xls")) {
			list = Excel.readExcel2003(is);
		} else {
			list = Excel.readExcel2007(is);
		}
		for (int i=0,j=list.size();i<j;i++){
			List<Object> row = list.get(i);
			ginsengMap.put("name", row.get(0).toString());
			ginsengMap.put("sex", row.get(1).toString());
	        ginsengMap.put("email", row.get(2).toString());
	        ginsengMap.put("dept_id", row.get(3).toString());
	        excelMapper.InputExcel(ginsengMap);
		}
		return "01";
	}

	@Override
	public List<EmpT> OutputExcel() {
		return excelMapper.getAll();
	}

mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wei.dao.ExcelMapper">
	<resultMap id="BaseResultMap" type="com.wei.entity.EmpT">
		<id column="id" jdbcType="INTEGER" property="id" />
		<result column="name" jdbcType="VARCHAR" property="name" />
		<result column="sex" jdbcType="CHAR" property="sex" />
		<result column="email" jdbcType="VARCHAR" property="email" />
		<result column="dept_id" jdbcType="INTEGER" property="deptId" />
	</resultMap>

	<resultMap type="com.wei.entity.EmpT" id="WithDeptResultMap">
		<id column="id" jdbcType="INTEGER" property="id" />
		<result column="name" jdbcType="VARCHAR" property="name" />
		<result column="sex" jdbcType="CHAR" property="sex" />
		<result column="email" jdbcType="VARCHAR" property="email" />
		<result column="dept_id" jdbcType="INTEGER" property="deptId" />
		<!-- 指定聯合查詢出的部門欄位的封裝 -->
		<association property="deptName" javaType="com.wei.entity.DeptT">
			<id column="d_id" property="dId" />
			<result column="d_name" property="dName" />
		</association>
	</resultMap>

	<insert id="InputExcel">
		insert into wei.emp_t (name,sex,email,dept_id) values
		(#{name },#{sex },#{email },#{dept_id },)
	</insert>

	<sql id="WithDept_Column_List">
		e.id, e.name, e.sex, e.email, e.dept_id, d.d_id, d.d_name
	</sql>

	<sql id="Example_Where_Clause">
		<where>
			<foreach collection="oredCriteria" item="criteria" separator="or">
				<if test="criteria.valid">
					<trim prefix="(" suffix=")" prefixOverrides="and">
						<foreach collection="criteria.criteria" item="criterion">
							<choose>
								<when test="criterion.noValue">
									and ${criterion.condition}
								</when>
								<when test="criterion.singleValue">
									and ${criterion.condition} #{criterion.value}
								</when>
								<when test="criterion.betweenValue">
									and ${criterion.condition} #{criterion.value} and
									#{criterion.secondValue}
								</when>
								<when test="criterion.listValue">
									and ${criterion.condition}
									<foreach collection="criterion.value" item="listItem"
										open="(" close=")" separator=",">
										#{listItem}
									</foreach>
								</when>
							</choose>
						</foreach>
					</trim>
				</if>
			</foreach>
		</where>
	</sql>

	<select id="getAll" resultMap="WithDeptResultMap">
		select
		<if test="distinct">
			distinct
		</if>
		<include refid="WithDept_Column_List" />
		FROM emp_t e
		left join dept_t d on e.`dept_id`=d.`d_id` order by e.id
		<if test="_parameter != null">
			<include refid="Example_Where_Clause" />
		</if>
	</select>

</mapper>

4,解析excel的工具類:

excel檔案傳至服務端:

public static String upload(HttpServletRequest request, HttpServletResponse response) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(MAX_REQUEST_SIZE);
		upload.setHeaderEncoding("UTF-8");
		String uploadPath = request.getSession().getServletContext().getRealPath("/") + UPLOAD_DIRECTORY;
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> formItems = upload.parseRequest(request);
			if (formItems != null && formItems.size() > 0) {
				for (FileItem item : formItems) {
					if (!item.isFormField()) {
						String fileName = new File(item.getName()).getName();
						filePath = uploadPath + File.separator + fileName;
						File storeFile = new File(filePath);
						item.write(storeFile);
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return filePath;
	}

讀取Excel檔案:

public static ArrayList<ArrayList<Object>> readExcel2003(InputStream is) {
		try {
			ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
			ArrayList<Object> colList;
			HSSFWorkbook wb = new HSSFWorkbook(is);
			HSSFSheet sheet = wb.getSheetAt(0);
			HSSFRow row;
			HSSFCell cell;
			Object value = null;
			for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
				row = sheet.getRow(i);
				colList = new ArrayList<Object>();
				if (row == null) {
					if (i != sheet.getPhysicalNumberOfRows()) {// 判斷是否是最後一行
						rowList.add(colList);
					}
					return rowList;
				} else {
					rowCount++;
				}
				for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
					cell = row.getCell(j);
					if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
						if (j != row.getLastCellNum()) {
							colList.add("");
						}
						continue;
					}
					if (null != cell) {
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC:
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
								break;
							} else {
								Double d = cell.getNumericCellValue();
								DecimalFormat df = new DecimalFormat("#.##");
								value = df.format(d);
							}
							break;
						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue();
							break;
						case HSSFCell.CELL_TYPE_BOOLEAN:
							value = cell.getBooleanCellValue() + "";
							break;
						case HSSFCell.CELL_TYPE_FORMULA:
							value = cell.getCellFormula() + "";
							break;
						case HSSFCell.CELL_TYPE_BLANK:
							value = "";
							break;
						case HSSFCell.CELL_TYPE_ERROR:
							value = "非法字元";
							break;
						default:
							value = "未知型別";
							break;
						}

					}
					colList.add(value);
				}
				rowList.add(colList);
			}
			if (is != null) {
				is.close();
			}
			return rowList;
		} catch (Exception e) {
			return null;
		}
	}

	public static ArrayList<ArrayList<Object>> readExcel2007(InputStream is) {
		try {
			ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
			ArrayList<Object> colList;
			XSSFWorkbook wb = new XSSFWorkbook(is);
			XSSFSheet sheet = wb.getSheetAt(0);
			XSSFRow row;
			XSSFCell cell;
			Object value = null;

			for (int i = sheet.getFirstRowNum() + 1, rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows(); i++) {
				row = sheet.getRow(i);
				colList = new ArrayList<Object>();
				if (row == null) {
					if (i != sheet.getPhysicalNumberOfRows()) {
						rowList.add(colList);
					}
					return rowList;
				} else {
					rowCount++;
				}
				for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
					cell = row.getCell(j);
					if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
						if (j != row.getLastCellNum()) {
							colList.add("");
						}
						continue;
					}

					if (null != cell) {
						switch (cell.getCellType()) {
						case HSSFCell.CELL_TYPE_NUMERIC:
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
								break;
							} else {
								Double d = cell.getNumericCellValue();
								DecimalFormat df = new DecimalFormat("#.##");
								value = df.format(d);
							}
							break;

						case HSSFCell.CELL_TYPE_STRING:
							value = cell.getStringCellValue();
							break;

						case HSSFCell.CELL_TYPE_BOOLEAN:
							value = cell.getBooleanCellValue() + "";
							break;

						case HSSFCell.CELL_TYPE_FORMULA:
							value = cell.getCellFormula() + "";
							break;

						case HSSFCell.CELL_TYPE_BLANK:
							value = "";
							break;

						case HSSFCell.CELL_TYPE_ERROR:
							value = "非法字元";
							break;

						default:
							value = "未知型別";
							break;
						}

					}
					colList.add(value);
				}
				rowList.add(colList);
			}
			if (is != null) {
				is.close();
			}
			return rowList;
		} catch (Exception e) {
			System.out.println("exception");
			return null;
		}
	}

匯出資料到excel並在瀏覽器下載:

public static String OutExcel(HttpServletRequest request, HttpServletResponse response, List<EmpT> list) throws Exception {

		String message = "fail";
		String dir = request.getSession().getServletContext().getRealPath("/output");
		File fileLocation = new File(dir);
		if (!fileLocation.exists()) {
			boolean isCreated = fileLocation.mkdir();
			if (!isCreated) {
			}
		}
		String webUrl = request.getSession().getServletContext().getRealPath("/output");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd mm-ss");
		String createExcelname = df.format(new Date()) + "OutputExcel.xls";
		String outputFile = webUrl + File.separator + createExcelname;
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		workbook.setSheetName(0, "emp");
		HSSFRow row1 = sheet.createRow(0);
		HSSFCell cell0 = row1.createCell(0, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell1 = row1.createCell(1, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell2 = row1.createCell(2, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell3 = row1.createCell(3, HSSFCell.CELL_TYPE_STRING);
		HSSFCell cell4 = row1.createCell(4, HSSFCell.CELL_TYPE_STRING);
		
		cell0.setCellValue("id");
		cell1.setCellValue("name");
		cell2.setCellValue("sex");
		cell3.setCellValue("email");
		cell4.setCellValue("dept_id");
		response.setContentType("text/html;charset=UTF-8");

		for (int j = 0; j < list.size(); j++) {
			
			EmpT empt = new EmpT();
			empt = list.get(j);
			
			HSSFRow row = sheet.createRow(j + 1);
			HSSFCell c0 = row.createCell(0, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c1 = row.createCell(1, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c2 = row.createCell(2, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c3 = row.createCell(3, HSSFCell.CELL_TYPE_STRING);
			HSSFCell c4 = row.createCell(4, HSSFCell.CELL_TYPE_STRING);

			c0.setCellValue(empt.getId());
			c1.setCellValue(empt.getName());
			c2.setCellValue(empt.getSex());
			c3.setCellValue(empt.getEmail());
			c4.setCellValue(empt.getDeptName().getdName());
		}
		FileOutputStream fOut = new FileOutputStream(outputFile);
		workbook.write(fOut);
		fOut.flush();
		fOut.close();
		File f = new File(outputFile);
		if (f.exists() && f.isFile()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				URLEncoder.encode(f.getName(), "utf-8");
				byte[] b = new byte[fis.available()];
				fis.read(b);
				response.setCharacterEncoding("utf-8");
				response.setHeader("Content-Disposition", "attachment; filename=" + createExcelname + "");
				ServletOutputStream out = response.getOutputStream();
				out.write(b);
				out.flush();
				out.close();
				if (fis != null) {
					fis.close();
				}
				f.delete();
				message = "success";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return message;
	}

5,關鍵程式碼到此完成,執行一下看看:

選擇excel匯入,服務端就會將excel中的資料讀取插入到資料庫中,

Excel檔案:

資料庫:

專案結束,excel檔案資料成功匯入的資料庫中。

獲取更多教程,請持續關注我的部落格。