《JavaWeb---简单应用---练习JDBC,JSTL》---上传Excel文件,利用工具包解析,将数据储存到数据库中,可以查询删除
2012-10-27 23:10
1031 查看
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>上传查看表格</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> body{ text-align: center; } table,td{ height: 30px; text-align: center; border: 1px green solid; border-collapse: collapse; } </style> </head> <body> <table> <tr style="color: red"> <td>说明</td> <td>操作</td> </tr> <tr> <td> 查看数据库中的数据</td> <td> <a href="${pageContext.request.contextPath }/servlet/Read" >查看</a> </td> </tr> <tr> <td> 管理数据库中的数据</td> <td> <a href="${pageContext.request.contextPath }/servlet/Control" >管理</a> </td> </tr> <tr> <form action="${pageContext.request.contextPath }/servlet/Receive" enctype="multipart/form-data" method="post"> <td> <input type="file" name="filexls"/><br/> </td> <td> <input type="submit" value="上传"/> </td> </form> </tr> </table> </body> </html>
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<FileItem> 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<User> 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<User> sava2Bean(FileItem item){ HSSFWorkbook hwb = null; try { //得到上传的文件 hwb = new HSSFWorkbook(item.getInputStream()); } catch (Exception e) { throw new RuntimeException("获取文件失败!"); } //获取一个表 HSSFSheet sheet = hwb.getSheetAt(0); //创建储存数据的集合 ArrayList<User> users = new ArrayList<User>(); //解析表中的数据,并将数据封装 for (int i = 1; i <= sheet.getLastRowNum(); i++){ HSSFRow row = sheet.getRow(i); //暂时储存一行数据 ArrayList<String> data = new ArrayList<String>(); 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<User> 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<User> readUsers(){ ArrayList<User> users = new ArrayList<User>(); 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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <c:if test="${requestScope.type == 0}" var="condition" scope="request"> <meta http-equiv="Refresh" content="3;url=${pageContext.request.contextPath }"/> </c:if> <title>显示信息</title> <meta http-equiv="description" content="this is my page"/> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/css/showusers.css"/> </head> <body> <c:if test="${requestScope.type == 0}" var="condition" scope="request"> <h1>上传成功</h1> 3秒后未跳转,<a href="${pageContext.request.contextPath }">点击这里...</a> </c:if> <c:if test="${requestScope.type == 1}" var="condition" scope="request"> <h1>数据库中的信息</h1> </c:if> <c:if test="${requestScope.type == 2}" var="condition" scope="request"> <h1>管理信息</h1> </c:if> <c:if test="${requestScope.control == 'delete'}" var="condition" scope="request"> <font color="red">删除成功!</font> </c:if> <table border="1" width="50%" > <tr style="background-color: #00FF00;"> <td>id</td><td>name</td><td>age</td><td>phone</td><td>email</td><c:if test="${requestScope.type == 2}" var="condition" scope="request"><td>control</td></c:if> </tr> <c:forEach var="user" items="${users }" varStatus="i"> <tr class="${i.count%2==0? 'even':'odd' }"> <td>${user.id }</td> <td>${user.name }</td> <td>${user.age }</td> <td>${user.phone }</td> <td>${user.email }</td> <c:if test="${requestScope.type == 2}" var="condition" scope="request"><td> <a href="${pageContext.request.contextPath }/servlet/Delete?id='${user.id }'">删除</a></td> </c:if> </tr> </c:forEach> </table> <c:if test="${requestScope.type == 1 || requestScope.type == 2}" var="condition" scope="request"> <a href="${pageContext.request.contextPath }">返回</a> </c:if> </body> </html>
相关文章推荐
- 利用集合完成象数据库那样存储数据,并且可以简单查询,利用map存储学生信息
- struts2上传excel文件并解析数据插入数据库
- 练习题——Gson解析、利用JDBC连接数据库进行数据的存取及查询等的综合
- springMvc 中 Excel批量数据上传,利用POI解析数据保存入数据库 及模板文件下载
- input file 文件上传下载 查询数据库数据并导出Excel
- SpringMVC简单实现上传Excel文件,并将Excel中的数据导入数据库
- 上传,解析Excel文件并保存数据到数据库
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- 【Servlet】在Servlet3.0中利用json+ajax把数据库查询出来的数据推向前台显示,无额外的json解析包
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- Android客户端上传数据到服务器:可以上传简单的表单,也可以方便的上传带有附件的文件
- java Excel 文件解析存入数据库 整型数据被整成科学记数法
- awt可视化界面上传数据到mysql,jsp通过jdbc方式查询数据库,并将结果打印在网页上
- 上传xls文件并解析数据存入msyql数据库
- C# 对sharepoint 列表的一些基本操作,包括添加/删除/查询/上传文件给sharepoint list添加数据
- JDBC保存EXCEL数据到数据库(2.数据表,Excel文件及javaBean准备)
- ASP.NET MVC4上传文件,并将excel内容导入数据库,导入后删除文件
- Excel文件上传服务器并解析存入数据库的整套过程(2003--2013都可试)
- java利用jdbc连接数据库之删除数据库中的数据
- 《JavaWeb---简单应用---服务器向客户端提供音乐资源(三)》--- 利用struts实现文件下载,下载时改变文件的名称