java实现excel表格导入数据库表

java学习 专栏收录该内容
6 篇文章 0 订阅

导入excel就是一个上传excel文件,然后获取excel文件数据,然后处理数据并插入到数据库的过程

一、上传excel

前端jsp页面,我的是index.jsp

  在页面中我自己加入了一个下载上传文件的功能,其中超链接就是下载

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="jquery/1.7.2/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery/jquery.form.js"></script>
<script type="text/javascript">



function test1(){
	var form = new FormData(document.getElementById("uploadForm"));
    $.ajax({
    	contentType:"multipart/form-data",
        url:"servlet/UploadHandleServlet",
        type:"post",
        async:false,
        data:form,
        dataType:"json",
        processData: false,  // 告诉jQuery不要去处理发送的数据
        contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
        success:function(data){
        	var result=eval(data);
			var filePath=result[0].filePath;
            //alert(filePath);
            var fileName = result[0].imageName;
            $("#download").attr("href","servlet/DownLoadServlet?filePath="+filePath);
            document.getElementById("download").innerHTML = fileName; 
            
            //上传文件后得到路径,然后处理数据插入数据库表中
            importExcel(filePath); 
        }
    }); 
}

function importExcel(filePath){
	$.ajax({
        url:"${pageContext.request.contextPath}/user/insertUserByExcelPath",
        type:"post",
        data:{"filePath":filePath},
        success:function(data){
        }
    });
}

</script>
<body>

导入excel表格
<form id="uploadForm" action="" method="post" enctype="multipart/form-data"> 
	<table>  
	     <tr>  
	          <td>上传文件:</td>  
	          <td>
	          <input type="file" name="fileName" id="fileName"/>
	          </td>  
	     </tr>
	</table>
</form>
<button id="uploadFile" onclick="test1();">确定</button>
<!-- servlet/DownLoadServlet -->
上传的文件<a id="download" href=""></a>
</body>
</html>

 后端的上传的servlet,其中需要commons-fileupload-1.2.1.jar的支持,然后我的保存路径savePath是自己写的一个配置文件来的,这里可以写上自己的上传文件所保存的路径就行,返回的是一个json,包括文件路径还有文件名

package com.huang.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.DiskFileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;

import com.huang.entity.User;
import com.huang.utils.Excel2Bean;
import com.huang.utils.PropertiesUtil;

/**
 * Servlet implementation class UploadHandleServlet
 */
@WebServlet("/UploadHandleServlet")
public class UploadHandleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadHandleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("进入servlet");
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("UTF-8");
		// 获取多个上传文件
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 遍历上传文件写入磁盘
		Iterator it = fileList.iterator();
		while (it.hasNext()) {
			Object obit = it.next();
			if (obit instanceof DiskFileItem) {
				DiskFileItem item = (DiskFileItem) obit;
				// 如果item是文件上传表单域
				// 获得文件名及路径
				String fileName = item.getName();
				if (fileName != null) {
					String fName = item.getName().substring(
							item.getName().lastIndexOf("\\") + 1);
					String formatName = fName
							.substring(fName.lastIndexOf(".") + 1);// 获取文件后缀名
					String savePath = PropertiesUtil.getInstance().getProperty("uploadFile");
//					String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
					File expsfile = new File(savePath);
					if (!expsfile.exists()) {// 创建文件夹
						expsfile.mkdirs();
					}
					
					String realPath = savePath+"/"+ UUID.randomUUID().toString()+"."+formatName;
					System.out.println("realPath:"+realPath);
					BufferedInputStream bis = new BufferedInputStream(
							item.getInputStream());// 获得文件输入流
					BufferedOutputStream outStream = new BufferedOutputStream(
							new FileOutputStream(new File(realPath)));// 获得文件输出流
					Streams.copy(bis, outStream, true);// 开始把文件写到你指定的上传文件夹
					// 上传成功,则插入数据库
					File file = new File(realPath);
					if (file.exists()) {
//						request.setAttribute("realPath", realPath);
//						request.getRequestDispatcher("/user/insertUserByExcelPath").forward(request, response);
						// 返回文件路径
						String imageName = file.getName();
						String json = "[{\"filePath\":\""
								+ realPath
								+ "\",\"imageName\":\"" + imageName + "\"}]";
						response.reset();
						response.setContentType("text/json");
						response.setCharacterEncoding("UTF-8");
						response.getWriter().write(json);
//						response.getWriter().write(realPath);
						response.getWriter().flush();
					}

				}
			}
		}
	}
	
}

二、处理excel表格并得到含有Javabean的list

在用ajax调用servlet上传文件后得到路径和文件名,然后进行excel数据处理,在前端的页面上调用importExcel()的js函数,传入刚刚得到的文件路径

我这里用的是ssm框架中的controller(我自己也学习一下),这里也可以用servlet,或者Struts等。能访问到后端服务就行。

这里是controller中的代码,主要数据处理在Excel2Bean.getBeanByExcelPath(filePath, User.class)这个方法中

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.huang.entity.User;
import com.huang.service.UserService;
import com.huang.utils.Excel2Bean;

@Controller("/userController")
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	Excel2Bean excel2Bean;
	
	@Resource(name="userService")
	UserService userService;

    @RequestMapping("/insertUserByExcelPath")
	public void insertUserByExcelPath(HttpServletRequest req,HttpServletResponse Resp){
		System.out.println("进入insertUserByExcelPath");
		String filePath = req.getParameter("filePath");
		System.out.println("filePath:"+filePath);
		List<User> list =Excel2Bean.getBeanByExcelPath(filePath, User.class);
		excel2Bean.testinsert(list);
	}
}

这里就说说Excel2Bean.getBeanByExcelPath(filePath, User.class)这个方法

从excel表格中获取数据然后转换成一个javaBean的list集合,代码中操作excel表格需要用到的jar  poi-ooxml-3.9-20121203.jar,poi-3.9-20121203.jar,poi-ooxml-schemas-3.9-20121203.jar,为什么要用到这些jar,因为在有些之前的版本的poi中可能对word的版本不能兼容,网上具体有说到这个。最好是用org.apache.poi.ss.usermodel.Workbook这个来操作excel,poi各种版本官网下载可以参考微博https://mp.csdn.net/postedit/83620739。对于getBeanByExcelPath这个方法使用到了泛型,也使用到了一点点的反射的东西,获取一个类的属性,并给属性赋值。代码中有方法测试这个获取Javabean的属性并赋值的方法。这个方法也是为了能更通用一点,适用于更多的javabean,更多的表。当然excel的表头就要用到Javabean中的属性名称了。如果对泛型不是很了解的可以学习一下,当然也可以先看里面的readExcel(filePath)这个方法,是一个固定的Javabean对象

代码如下

package com.huang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.model.Workbook;
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.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Component;

import com.huang.entity.User;
import com.huang.service.UserService;

@Component
public class Excel2Bean {
	
	@Resource(name="userService")
	UserService userService;
	
	public static Excel2Bean excel2Bean;

	@PostConstruct
	public void init() {
		excel2Bean = this;
	}
	public static void testinsert(List<User> list){
		if(list!=null&&list.size()>0){
			for (User user : list) {
				user.setId(excel2Bean.userService.getMaxId()+1);
				excel2Bean.userService.insertUserByUser(user);
			}
		}
//		System.out.println(excel2Bean.userService.getMaxId());
		
	}
	
	/**  
     * 获取属性名数组  
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws SecurityException 
     * */  
    public static  String[]  getFiledName(Class<?> clazz) throws SecurityException, InstantiationException, IllegalAccessException{
    	
        Field[] fields=clazz.newInstance().getClass().getDeclaredFields();  
        String[] fieldNames=new String[fields.length];  
        for(int i=0;i<fields.length;i++){  
//            System.out.println(fields[i].getType());  
            fieldNames[i]=fields[i].getName();  
        }  
        return fieldNames;  
    } 


	public static <T>T getByExcelPath(String excelPath,Class<T> clazz){
		T bean = null;
		try {
			bean = clazz.newInstance();
			String tableName = clazz.getSimpleName();
			// 反射bean上与列名相同的属性
			try {
				Field f = bean.getClass().getDeclaredField("name");
				f.setAccessible(true);
				f.set(bean, "兽王");
//				System.out.println(f);
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bean;
	}
	
	public static <T> List<T> getBeanByExcelPath(String excelPath,Class<T> clazz){
		List<T> list = new ArrayList<T>();
		org.apache.poi.ss.usermodel.Workbook workbook = null;
		InputStream is = null;
		try {
			is = new FileInputStream(excelPath);
			workbook = WorkbookFactory.create(is);
			is.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		// 循环工作表
		for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
			Sheet sheet = workbook.getSheetAt(numSheet);//得到工作表
			if (sheet == null) {
				continue;
			}
			// 循环行  因为表头行是第0行,所以从0开始循环
			Row rowHead = sheet.getRow(0);
			for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
				T bean = null;
				try {
					bean = clazz.newInstance();
				} catch (InstantiationException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Row row = sheet.getRow(rowNum);//得到行
				short s = row.getLastCellNum();//得到此行有多少列
				for (int i = 0; i < s; i++) {
					Cell cell = row.getCell(i);//得到单元格(每行)
					Cell cellHead = rowHead.getCell(i);
					String feild = (String) getCellValObject(cellHead);//得到表头属性名称
					Object value = getCellValObject(cell);
					Field f = null;
					try {
						
						f = bean.getClass().getDeclaredField(feild);//根据名称获取bean中的属性
						f.setAccessible(true);
						f.set(bean, value);//给属性赋值
					} catch (NoSuchFieldException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
				}
				
				//把所有属性值添加完成后装入list中
				list.add(bean);
				
			}
		}
		
		
		return list;
	}
	
	public static String getCellVal(HSSFCell cel) {
		if(cel.getCellType() == HSSFCell.CELL_TYPE_STRING) {
			return cel.getRichStringCellValue().getString();
		}
		if(cel.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
			return cel.getNumericCellValue() + "";
		}
		if(cel.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
			return cel.getBooleanCellValue() + "";
		}
		return cel.toString();
	}
	
	public static String getCellVal(Cell cel) {
		if(cel.getCellType() == Cell.CELL_TYPE_STRING) {
			return cel.getRichStringCellValue().getString();
		}
		if(cel.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			return cel.getNumericCellValue() + "";
		}
		if(cel.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return cel.getBooleanCellValue() + "";
		}
		if(cel.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return cel.getCellFormula() + "";
		}
		return cel.toString();
	}
	
	public static Object getCellValObject(Cell cel) {
		if(cel.getCellType() == Cell.CELL_TYPE_STRING) {
			return cel.getRichStringCellValue().getString();
		}
		if(cel.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			return new Integer(Double.valueOf(cel.getNumericCellValue()).intValue());
		}
		if(cel.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return cel.getBooleanCellValue() + "";
		}
		if(cel.getCellType() == Cell.CELL_TYPE_FORMULA) {
			return cel.getCellFormula() + "";
		}
		return null;
	}
	
	public static List<User> readExcel(String filePath){
		List<User> list = new ArrayList<User>();
//	    HSSFWorkbook workbook = null;
		org.apache.poi.ss.usermodel.Workbook workbook = null;
	    try {
	      // 读取Excel文件
	      InputStream inputStream = new FileInputStream(filePath);
//	      workbook = new HSSFWorkbook(inputStream);
	      workbook = WorkbookFactory.create(inputStream);
	      inputStream.close();
	    } catch (Exception e) {
	      e.printStackTrace();
	    }
	    // 循环工作表
	    for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
	      Sheet hssfSheet = workbook.getSheetAt(numSheet);
	      if (hssfSheet == null) {
	        continue;
	      }
	      // 循环行
	      for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
	        Row hssfRow = hssfSheet.getRow(rowNum);
//	        System.out.println("hssfRow1:"+hssfRow.getRowNum());
//	        System.out.println("hssfRow2:"+hssfRow.getLastCellNum());
	        if (hssfRow == null) {
	          continue;
	        }
	        // 将单元格中的内容存入集合
	        User user = new User();
	        Cell cell = hssfRow.getCell(0);
	        if (cell == null) {
	          continue;
	        }
	        String name = getCellVal(cell);
	        System.out.println("name:"+name);
	        user.setName(name);
	        cell = hssfRow.getCell(1);
	        if (cell == null) {
	          continue;
	        }
	        String age = getCellVal(cell);
	        Integer aa = Double.valueOf(age).intValue();
	        
	        System.out.println("age:"+age);
	        user.setAge(Double.valueOf(age).intValue());
	        list.add(user);
	      }
	    }
	    return list;
	}
}

三、插入数据库

得到excel转换成Javabean的list对象后然后插入到数据库中。我这里用的是ssm里面的一些操作,我自己可能都解释不清楚。反正得到数据,然后往数据库插入数据这个操作也可以用其他方式的,框架也好,jdbc连接数据库直接去执行sql也好,都OK。

最后贴一下下载上传的文件的servlet代码

package com.huang.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

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

/**
 * Servlet implementation class DownLoadServlet
 */
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 下载文件
//		String path = "d:"+File.separator + "mytestfile" + File.separator + "testFile.txt";
		String path = request.getParameter("filePath");
		String realPath = path.substring(path.lastIndexOf("\\")+1);  
		response.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(realPath, "utf-8"));  
        //获取到所下载的资源  
		FileInputStream fis = new FileInputStream(path);
		if(fis!=null){
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = fis.read(buf)) != -1) {
				response.getOutputStream().write(buf, 0, len);
			}
			fis.close();
		}else{
			response.getWriter().write("服务器上面不存在该文件");
		}
		
	}

}

还有User.java这个javabean

public class User {
	private Integer id;
	 
    private String name;
 
    private Integer age;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

页面效果如下,超链接可以下载,点击确定后上传文件并取数据然后插入数据库表中 

excel表格形式如下 

 

 

nameage
大鱼18
小鱼15

 

文章不知道有什么遗漏的地方,有的话,还请多多指教。

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

summerdirewof

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值