excel文件上传保存到数据库前后端
上传的excel文件数据

依赖
<dependencies>
<!--<!– xls(03) –>-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<!-- xlsx(07) -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
<!--日期格式化工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
前端
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/e" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload"/>
</form>
</body>
</html>
info.jsp
- 提示信息,可以不要
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
后端
pojo
- Product
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private Integer pid;
private String pname;
private double price;
private int pstock;
}
dao
- DBConnection 连接数据库
package com.tian.dao;
import java.sql.*;
//类不能被其它类继承
public final class DBConnection {
private static final String URL = "jdbc:mysql://localhost:3306/poi";
private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String USER_NAME = "root";
private static final String USER_PSW = "root";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// final:最终形态,不能被子类重写
public static final Connection getDBConnection() throws SQLException {
return DriverManager.getConnection(URL, USER_NAME, USER_PSW);
}
public static final void close(Connection conn, PreparedStatement pstm, ResultSet rs) {
close(rs);
close(pstm);
close(conn);
}
private static final void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static final void close(PreparedStatement pstm) {
if (pstm != null) {
try {
pstm.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static final void close(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
- ProductDao
package com.tian.dao;
import com.tian.pojo.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ProductDao {
private Connection conn;
private PreparedStatement pstm;
private ResultSet rs;
public void save(Product product) {
String strSQL = "insert into poi values (?,?,?,?)";
try {
conn = DBConnection.getDBConnection();
pstm = conn.prepareStatement(strSQL);
pstm.setInt(1, product.getPid());
pstm.setString(2,product.getPname());
pstm.setDouble(3,product.getPrice());
pstm.setInt(4,product.getPstock());
pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.close(conn, pstm, rs);
}
}
}
service
- ProductService
public class ProductService {
private ProductDao productDao=new ProductDao();
public void save(List<Product> productList) {
for (Product product:productList){
productDao.save(product);
}
}
}
servlet
- ExcelServlet
package com.tian.servlet;
import com.tian.pojo.Product;
import com.tian.service.ProductService;
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.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(1);//给你确定一下确实进来了
//--------------------
String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath + "目录不存在,需要创建");
file.mkdir();
}
String filename="";
String msg = "";
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(req)) {
return;
}
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println(name + "=" + value);
} else {
filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
filename = filename.substring(filename.lastIndexOf("\\") + 1);
InputStream in = item.getInputStream();
FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
item.delete();
msg = "文件上传成功!";
}
}
} catch (Exception e) {
msg = "文件上传失败!";
e.printStackTrace();
}
//-------------------
String url =savePath+"\\"+filename;
System.out.println(url);
List<Product> productList = read(url);
System.out.println(productList);
ProductService productService = new ProductService();
productService.save(productList);
System.out.println("已存入数据库中");
req.setAttribute("msg", msg);
req.getRequestDispatcher("/info.jsp").forward(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
public static List<Product> read(String path) throws IOException {
List<Product> productList=new ArrayList<Product>();
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(path);
XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
if(row!=null){
List<String> list = new ArrayList<String>();
for(Cell cell:row){
if(cell!=null){
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();
if(value!=null&&!"".equals(value)){
list.add(value);
}
}
}
if(list.size()>0){
Product product = new Product(Integer.parseInt(list.get(0)), list.get(1), Double.parseDouble(list.get(2)), Integer.parseInt(list.get(3)));
productList.add(product);
}
}
}
return productList;
}
}
web.xml
<servlet>
<servlet-name>ExcelServlet</servlet-name>
<servlet-class>com.tian.servlet.ExcelServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ExcelServlet</servlet-name>
<url-pattern>/e</url-pattern>
</servlet-mapping>
使用Apache POI处理Excel并上传至数据库的Java实现
该博客详细介绍了如何在Java环境中利用Apache POI库读取Excel文件,并将数据上传到MySQL数据库。首先,展示了所需的依赖项,包括POI、Lombok、JUnit等。接着,提供了前端JSP页面用于文件上传,后端通过Servlet接收文件,解析Excel内容并保存到数据库中。最后,展示了一个简单的数据库连接和关闭方法。
546

被折叠的 条评论
为什么被折叠?



