博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
上传excel文件到服务器
阅读量:4290 次
发布时间:2019-05-27

本文共 5027 字,大约阅读时间需要 16 分钟。

最近遇到了需要上传excel文件,并将excel表中的数据都出来,存到数据库中的需求,今天将步骤整理一下,如下:

一、新建一个html(或jsp页面),如:uploadExcel.html,代码如下:

导入Excel表

选择Excel表:

2、在web.xml中配置servlet和servlet-mapping,代码如下:

uploadExcel
com.shop.upload.UploadServlet
filePath
store
tempFilePath
temp
uploadExcel
/uploadExcel
3、servlet类代码如下:

package com.upload;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.servlet.ServletConfig;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;/** * 上传文件的servlet类 */public class UploadServlet extends HttpServlet{	/**	 * @function:Excel 表格上传	 */	private String filePath;  //存放上传文件的目录	private String tempFilePath;//存放临时文件的目录	@Override	public void init(ServletConfig config) throws ServletException {		super.init(config);		//读取初始化参数filePath		filePath=config.getInitParameter("filePath");		//读取初始化参数tempFilePath		tempFilePath=config.getInitParameter("tempFilePath");		filePath=getServletContext().getRealPath(filePath);		tempFilePath=getServletContext().getRealPath(tempFilePath);	}	@Override	protected void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		response.setContentType("text/html; charset=GBK");		response.setHeader("Cache-Control", "no-cache");		response.setCharacterEncoding("GBK");		PrintWriter out = response.getWriter();		try {			//创建一个基于硬盘的FileItem工厂			DiskFileItemFactory factory=new DiskFileItemFactory();			//设置向硬盘写数据时所用的缓冲区的大小,暂定10M,一会再改			factory.setSizeThreshold(1000*1024);			//设置临时目录			factory.setRepository(new File(tempFilePath));						//创建一个文件上传处理器			ServletFileUpload upload=new ServletFileUpload(factory);			//设置允许上传的文件的最大尺寸,暂定10M,一会再改			upload.setSizeMax(1000*1024);					Map
params = new HashMap
();// 存放请求参数 List
items=upload.parseRequest(request); Iterator iter=items.iterator(); while(iter.hasNext()){ FileItem item=(FileItem) iter.next(); if(item.isFormField()){ processFormField(item,params); //处理普通的表单域 }else{ processUploadFile(item,params); //处理上传文件 } } String path=params.get("path"); int total=getExcelTotal(path); out.println("

点击'确认'按钮继续

"); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); out.println("

上传出错--点击'取消'按钮

"); out.flush(); out.close(); } } /** * 获得excel中数据总数 * @param path * @return */ public int getExcelTotal(String path) { final Sheet sheet; final Workbook book; int total=0; try { // t.xls为要读取的excel文件名 book = new VillageHouses().getWorkBookObject(path) ; // 获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....) sheet = book.getSheetAt(0) ; total = sheet.getLastRowNum() ; } catch (Exception e) { e.printStackTrace(); } return total; } /** * 处理上传文件 * @param item * @param params * @throws IOException */ private void processUploadFile(FileItem item, Map
params) throws IOException { createFileDirectory(filePath); String fileName = item.getName() ; String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length()); long time = System.currentTimeMillis();// 时间毫秒数 String savePath = filePath +"/"+ time + fileType; System.out.println("服务器文件路径:"+savePath); InputStream inputStream = item.getInputStream();// 获取文件流 FileOutputStream outputStream = new FileOutputStream(savePath);// 创建输出流 byte[] tyte = new byte[1024]; int len = 0; while ((len = inputStream.read(tyte)) > 0) { outputStream.write(tyte, 0, len); } inputStream.close(); outputStream.close(); item.delete();// 删除临时文件 params.put("path", savePath); } /** * 处理表单数据 * @param item * @param params */ private void processFormField(FileItem item, Map
params) { String name=item.getFieldName();//获得表单域的名字 String value=item.getString(); //获得表单域的值 if("xqid".equals(name)) params.put("xqid", value); if("id".equals(name)) params.put("id", value); } /** * 判断项目所在服务器上的文件夹是否创建 * @param path */ private void createFileDirectory(String path) { File file = new File(path); if (!file.exists()) { // 创建文件夹 file.mkdirs(); } } }
这个就是jsp负责页面,servlet负责实现具体的上传功能,代码中有标注,很简单,应该都可以看懂

转载地址:http://hwqgi.baihongyu.com/

你可能感兴趣的文章
全网最详细的一篇SpringCloud总结
查看>>
消息中间件中的有序消息,其实是排队但是不能插队
查看>>
不知道分布式事务,还想进互联网大厂
查看>>
mysql为什么使用B+树作为索引的结构
查看>>
mysql索引总结(1)-mysql 索引类型以及创建(文章写的不错!!!)
查看>>
聊聊CAS - 面试官最喜欢问的并发编程专题
查看>>
Spring Boot 中使用一个注解轻松将 List 转换为 Excel 下载
查看>>
高并发环境下,先操作数据库还是先操作缓存?
查看>>
MySQL Explain详解
查看>>
一直搞不清楚什么是读写分离,主从复制的原理,今天总算搞懂了
查看>>
消息队列 mq 必会面试题
查看>>
线程池的工作原理是啥?能手写一个线程池吗?
查看>>
一口气说出 6种 延时队列的实现方案,大厂offer稳稳的
查看>>
原来redis这么简单,跟着文章操作一遍你就会了
查看>>
Redis两种持久化机制RDB和AOF详解(面试常问,工作常用)
查看>>
事务隔离级别中的可重复读能防幻读吗?
查看>>
老伙计,关于JDK并发包,这些不为人知的秘密你知道多少?
查看>>
图片的左右切换
查看>>
进级的RecyclerView——LRecyclerView
查看>>
Android 利用Gradle实现app的环境分离
查看>>