1. 程式人生 > >使用POI實現上傳ecxel檔案,並讀取其中資料並存入資料庫

使用POI實現上傳ecxel檔案,並讀取其中資料並存入資料庫

首先是檢視層 即 jsp
<span style="font-size:14px;"><body>
	<h1>${err}</h1>
	<form action="<%=basePath%>uploadServlet" method="post" enctype="multipart/form-data">
		文件讀取: <input type="file" name="biaodan"><br> 
		<input type="submit" value="上傳">
	</form>
</body></span>

然後是jar包:

commons-collections4-4.1.jar
commons-fileupload-1.3.2.jar
commons-io-2.5.jar
mysql-connector-java-5.1.40-bin.jar
poi-3.15.jar
poi-ooxml-3.15.jar
poi-ooxml-schemas-3.15.jar
xmlbeans-2.6.0.jar

接著是Servlet ,當然得配置web.xml咯:
<span style="font-size:14px;"><servlet>
	<servlet-name>UploadServlet</servlet-name>
	<servlet-class>cn.c.Servlet.UploadServlet</servlet-class>
</servlet>

  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/uploadServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list></span>
public class UploadServlet extends HttpServlet {
UserService userService=new UserService();
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		ServletInputStream in = request.getInputStream();// 獲取流
		DiskFileItemFactory factory = new DiskFileItemFactory();// 例項化類
		ServletFileUpload sfu = new ServletFileUpload(factory);// 建立解析器
		try {
			List<FileItem> filetiemList = sfu.parseRequest(request);// 解析集合
			FileItem f = filetiemList.get(0);// 獲取檔名
			
			 String fileName=f.getName();
		      String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
		      if("xlsx".equals(prefix)){
		    		File file=new File(this.getServletConfig().getServletContext().getRealPath("/")+"WEB-INF/excel/"+f.getName());
					f.write(file);
					userService.read(file);
					file.delete();
					request.setAttribute("err","上傳成功");
		      }else {
				request.setAttribute("err","檔案格式不正確");
			}
		      
		
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			//轉發的地址
			request.getRequestDispatcher("jsp/Upload.jsp").forward(request, response);
			}
	}
}
然後是service也就是業務層咯:(其中型別轉換的方法提示過期,但是由於沒有給出新的方法所以就先用著了)
public class UserService {
	
	public void read(File file) throws IOException, IllegalArgumentException,
			IllegalAccessException, ClassNotFoundException, SQLException {
		UserDao userDao=new UserDao();
		// 獲取檔案
		InputStream is = new FileInputStream(file);
		// 建立物件
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		XSSFRow xssfRow;
		List<User> listUser = new ArrayList<User>();
		// 獲取每一個工作薄(頁)
		for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
			XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
			if (xssfSheet == null) {
				continue;
			}
			// 獲取當前工作薄的每一行
			for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
				xssfRow = xssfSheet.getRow(rowNum);
				User user = new User();
				// 獲取列
				for (int columnNum = 0; columnNum < xssfRow
						.getPhysicalNumberOfCells(); columnNum++)
					if (xssfRow != null) {
						// 讀取資料
						XSSFCell one = xssfRow.getCell(columnNum);
						String textUser = getValue(one);
						Field[] field = user.getClass().getDeclaredFields();
						// 依次賦值
						Field f = field[columnNum];
						f.set(user, textUser);
					}
				listUser.add(user);
			}
		}
		userDao.DB(listUser);
	}
	//型別轉換。
	private String getValue(XSSFCell xssfRow) {
		if (xssfRow.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(xssfRow.getBooleanCellValue());
		} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
			return String.valueOf(xssfRow.getNumericCellValue());
		} else {
			return String.valueOf(xssfRow.getStringCellValue());
		}
	}
}
還有Dao 也就是資料庫的連線:(我用的是mysql的jdbc)
public class UserDao {
	private Connection con;
	private PreparedStatement pstm;
	private String url = "jdbc:mysql://localhost:3306/test";
	private String className = "com.mysql.jdbc.Driver";
	private String username = "root";
	private String password = "";

	public void DB(List<User> listUser) throws ClassNotFoundException,
			SQLException {
		Class.forName(className);
		con = DriverManager.getConnection(url, username, password);

		String sql = "INSERT INTO u_user  VALUES(?,?,?)";
		for (int i = 0; i < listUser.size(); i++) {
			 pstm = con.prepareStatement(sql);
			 pstm.setString(1, listUser.get(i).getUsername());
			 pstm.setString(2, listUser.get(i).getPassword());
			 pstm.setString(3, listUser.get(i).getNike());
			 pstm.addBatch();
			 pstm.executeBatch();
		}
		
		con.close();

	}

}

最後實體類閃亮登場:

public class User {
	public String username;
	
	public String password;
	public String nike;


	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password
				+ ", nike=" + nike + "]";
	}

	public String getNike() {
		return nike;
	}

	public void setNike(String nike) {
		this.nike = nike;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public User() {
		super();
	}

	public void setPassword(String password) {
		this.password = password;
	}
}