《JavaWeb---简单应用---练习JDBC,JSTL》---上传Excel文件,利用工具包解析,将数据储存到数据库中,可以查询删除

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    上传查看表格
	
	
	    
	
	
	
	
  
  
  
  
说明 操作
查看数据库中的数据 查看
管理数据库中的数据 管理

package com.strong.upload.receive;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

import com.strong.upload.dao.DaoUtils;
import com.strong.upload.javabean.User;

public class Receive extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置编码
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart){
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			List  items = null;
			try {
				//转换请求数据
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				throw new RuntimeException("转换请求失败!");
			}
			//遍历请求
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
			    FileItem item = (FileItem) iter.next();

			    if (!item.isFormField()) {
			    	//判断是上传文件,并且是指定上传框内的文件
			    	if (item.getContentType().equals("application/vnd.ms-excel")){
				    	if (item.getFieldName().equals("filexls")){
				    		ArrayList users = sava2Bean(item);
				    		request.setAttribute("users", users);
				    		DaoUtils.createUsers(users);//将数据储存到数据库中
				    		//DaoUtils.readUsers();
				    	}else{
				    		System.out.println("文件名不正确");
				    	}
			    	}
			    }
			}
		}
		request.setAttribute("type", "0");
		request.getRequestDispatcher("/WEB-INF/jsp/showusers.jsp").forward(request, response);
	}
	public ArrayList sava2Bean(FileItem item){
		HSSFWorkbook hwb = null;
		try {
			//得到上传的文件
			hwb = new HSSFWorkbook(item.getInputStream());
		} catch (Exception e) {
			throw new RuntimeException("获取文件失败!");
		}
		//获取一个表
		HSSFSheet sheet = hwb.getSheetAt(0);
		//创建储存数据的集合
		ArrayList users = new ArrayList();
		
		//解析表中的数据,并将数据封装
		for (int i = 1; i <= sheet.getLastRowNum(); i++){
			HSSFRow row = sheet.getRow(i);
			//暂时储存一行数据
			ArrayList data = new ArrayList();
			for (int j = 0; j < row.getLastCellNum(); j++){
				HSSFCell cell = row.getCell(j);
				cell.setCellType(Cell.CELL_TYPE_STRING);
				data.add(cell.toString());
			}
			users.add(new User(data.get(0),data.get(1),data.get(2),data.get(3),data.get(4)));
			data.clear();
		}
		//以文件的形式保存到硬盘上
		String fallname = item.getName();
		String filename = fallname.substring(fallname.lastIndexOf("\\")+1, fallname.lastIndexOf("."));
		try {
			hwb.write(new FileOutputStream(new File("c:\\"+filename+"_upload.xls")));
		} catch (Exception e) {
			throw new RuntimeException("保存文件失败!");
		}
		return users;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}


 

package com.strong.upload.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.strong.upload.javabean.User;
/*
create table users(
id varchar(32) not null,
name varchar(32) not null,
age varchar(32) not null,
phone varchar(32) not null,
email varchar(32) not null
); 
 */
public class DaoUtils {
	static Connection conn = null;
	static Statement st = null;
	
	static {
		//建立连接
		conn = JdbcUtils.getConnection();
	
		//创建语句
		try {
			st = conn.createStatement();
		} catch (SQLException e) {
			throw new RuntimeException("创建语句失败!");
		}
	}
	
	public static void createUsers(ArrayList users){
		if (conn != null && st != null){
			for (int i = 0; i < users.size(); i++){
				User user = users.get(i);
				
				String sql = "insert into users(id,name,age,phone,email) values('"+
				user.getId()+"','"+user.getName()+"','"+user.getAge()+"','"+user.getPhone()+"','"+user.getEmail()+"')";
				try {
					st.executeUpdate(sql);
				} catch (SQLException e) {
					throw new RuntimeException("更新数据失败!");
				}
			}
		}
	}
	public static ArrayList readUsers(){
		ArrayList users = new ArrayList();
		if (conn != null && st != null){
			String sql = "select * from users";
			try {
				ResultSet rs = st.executeQuery(sql);
				while(rs.next()){
					String id = (String) rs.getObject("id");
					String name = (String) rs.getObject("name");
					String age = (String) rs.getObject("age");
					String phone = (String) rs.getObject("phone");
					String email = (String) rs.getObject("email");
					
					users.add(new User(id, name, age, phone, email));
				}
			} catch (SQLException e) {
				throw new RuntimeException("查询失败!");
			}
		}
		return users;
	}
	public static void deleteUser(String id){
		if (conn != null && st != null){
			String sql = "delete from users where id="+id;
			try {
				st.executeUpdate(sql);
			} catch (SQLException e) {
				throw new RuntimeException("删除失败!");
			}
		}
	}
}


 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>



  
    
		
	
    显示信息
    
    
    
    
    
  
  
	
	  

上传成功

3秒后未跳转,点击这里...
  

数据库中的信息

  

管理信息

  删除成功!
idnameagephoneemailcontrol
${user.id } ${user.name } ${user.age } ${user.phone } ${user.email } 删除
  返回



 

 


2016-9-1:有好多小伙伴想要源码。今天偶然间翻出来,就索性上传了。希望对大家有所帮助。

源码

你可能感兴趣的:(Java,Web)