jsp使用webuploader上传excel mysql导入导出 apache-POI

Posted 霜序0.2℃

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jsp使用webuploader上传excel mysql导入导出 apache-POI相关的知识,希望对你有一定的参考价值。

jsp使用webuploader上传excel mysql导入导出 apache-poi

关键词:jsp,webuploader,excel上传导入导出,mysql

目标

  • 让excel上传到服务器并让插入数据到数据库
  • 如果需要下载则将数据库中的数据导出成excel并成功让用户下载

效果

大致思路

前端实现:layui,webuploader,jsp
后端实现:apache.poi,mysql,servlet,fastjson,commons-io
日志组件:slf4j,log4j

前端使用layui来实现,用webuploader作上传组件上传excel,用apache-poi操作excel导入和导出,编写了一个工具类ExcelUtil

最开始从add.jsp开始,需要上传就到uploadservlet中,操作是将excel传到服务器并且存入数据库中(我加了一个id字段)

list.jsp即查看数据库中有多少个excel表格,数据是从data.jsp中传入的

如果需要下载则通过downloadservlet生成excel并下载

现在的我后知后觉,应该把那些顶部的abcde…设成字段,傻了傻了

代码

util

excelUtil

excel工具类

package top.sehnsucht.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import top.sehnsucht.dao.ExcelDao;
import top.sehnsucht.dao.impl.ExcelDaoImpl;
import top.sehnsucht.service.ExcelService;
import top.sehnsucht.service.impl.ExcelServiceImpl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * @Description: excel工具类
 * @Author: Cai
 * @CreateTime: 2021/11/19
 */

public class ExcelUtil 
    /**
     * 将name文件从数据库中读取出来
     * @throws IOException
     */
    public static void createExcelFile(String name, String path) throws Exception 
        ExcelDao dao = new ExcelDaoImpl();
        ArrayList<ArrayList<String>> allList = dao.dataToExcel(name);

        File excelFile = new File(path);
        if (!excelFile.exists()) 
            excelFile.mkdirs();
        

        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        CellStyle cellStyle = wb.createCellStyle();
        // 字体
        Font font = wb.createFont();
        font.setFontName("等线");
        font.setFontHeightInPoints((short) 20);
        cellStyle.setFont(font);
        for (int i = 0; i < allList.size(); i++) 
            // 3、创建行对象
            Row row = sheet.createRow(i);
            for (int j = 0; j < allList.get(i).size(); j++) 
                Cell cell = row.createCell(j);
                cell.setCellValue(allList.get(i).get(j));
                cell.setCellStyle(cellStyle);
            
        

        OutputStream os = new FileOutputStream(path + "\\\\" + name + ".xls");
        wb.write(os);
        os.close();
    

    /**
     * 将filePath的文件存入数据库
     * @param name
     * @param filePath
     * @throws IOException
     */
    public static void readExcelFile(String name, String filePath) throws IOException 
        ExcelDao dao = new ExcelDaoImpl();
        ExcelService service = new ExcelServiceImpl(dao);

        File xlsFile = new File(filePath);

        // 工作表
        Workbook workbook = WorkbookFactory.create(xlsFile);
        // 表个数。
        int numberOfSheets = workbook.getNumberOfSheets();
        // 遍历表。
        for (int i = 0; i < numberOfSheets; i++) 
            Sheet sheet = workbook.getSheetAt(i);

            // 行数。
            int rowNumbers = sheet.getLastRowNum() + 1;

            // Excel第一行。
            Row temp = sheet.getRow(0);
            if (temp == null) 
                continue;
            

            int cells = temp.getPhysicalNumberOfCells();

            ArrayList<String> list = new ArrayList<String>();
            // 读数据。
            for (int row = 0; row < rowNumbers; row++) 
                if (row == 0) 
                    Row r = sheet.getRow(row);
                    for (int col = 0; col < cells; col++) 
                        if (r.getCell(col) == null) 
                            list.add("null");
                         else 
                            list.add(r.getCell(col).toString());
                        
                    
                    System.out.println(list);
                    service.createExcel(name,list);
                    continue;
                
                ArrayList<String> data = new ArrayList<String>();
                Row r = sheet.getRow(row);
                for (int col = 0; col < cells; col++) 
                    if (r.getCell(col) == null) 
                        data.add("null");
                     else 
                        data.add(r.getCell(col).toString());
                    
                
                service.addExcel(name,list,data);
            
        
    


DBUtil

package top.sehnsucht.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/10/29
 */
@Slf4j
public class DBUtil 
    // 定义数据库连接参数
    public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/excel";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "818181";


    // 注册数据库驱动
    static 
        try 
            Class.forName(DRIVER_CLASS_NAME);
         catch (ClassNotFoundException e) 
            e.printStackTrace();
        
    

    // 获取连接
    public static Connection getConn() throws SQLException 
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    

    // 关闭连接
    public static void closeConn(Connection conn) 
        if (null != conn) 
            try 
                conn.close();
             catch (SQLException e) 
                System.out.println("关闭连接失败!");
                e.printStackTrace();
            
        
    

    //测试
    public static void main(String[] args) throws SQLException 
        System.out.println(DBUtil.getConn());
    

servlet

DownloadServlet

package top.sehnsucht;

import org.apache.log4j.Logger;
import top.sehnsucht.dao.ExcelDao;
import top.sehnsucht.dao.impl.ExcelDaoImpl;
import top.sehnsucht.service.ExcelService;
import top.sehnsucht.service.impl.ExcelServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/11/20
 */

public class DownloadServlet extends HttpServlet 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        Logger logger = Logger.getLogger(this.getClass());
        String path = req.getSession().getServletContext().getRealPath("/") + "\\\\excel";
        String name = req.getParameter("name");
        logger.info(path);
        logger.info(name);
        ExcelDao dao = new ExcelDaoImpl();
        ExcelService service = new ExcelServiceImpl(dao);
        service.DataToExcel(name,path);


        resp.setContentType("application/vnd.ms-excel");
        req.getRequestDispatcher("/excel/" + name + ".xls").forward(req,resp);

        req.getRequestDispatcher("/list").forward(req,resp);
    

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        doGet(req, resp);
    


JDBCServlet

package top.sehnsucht;

import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class JDBCServlet extends HttpServlet 
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort() + "/list.jsp";
        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        resp.setHeader("Location", strBackUrl);
    

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        doGet(req, resp);
    


Log4jServlet

package top.sehnsucht;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.File;


/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/11/12
 */

public class Log4JInitServlet extends HttpServlet 

    @Override
    public void init(ServletConfig config) throws ServletException 
        System.out.println("Log4JInitServlet 正在初始化 log4j日志设置信息");
        String log4jLocation = config.getInitParameter("log4j-properties-location");

        ServletContext sc = config.getServletContext();

        String str= sc.getInitParameter("test");
        System.out.println("str:"+str);

        if (log4jLocation == null) 
            System.err.println("*** 没有 log4j-properties-location 初始化的文件, 所以使用 BasicConfigurator初始化");
            BasicConfigurator.configure();
         else 
            String webAppPath = sc.getRealPath("/");
            String log4jProp = webAppPath + log4jLocation;
            File yoMamaYesThisSaysYoMama = new File(log4jProp);
            if (yoMamaYesThisSaysYoMama.exists()) 
                System.out.println("使用: " + log4jProp+"初始化日志设置信息");
                PropertyConfigurator.configure(log4jProp);
             else 
                System.err.println("*** " + log4jProp + " 文件没有找到, 所以使用 BasicConfigurator初始化");
                BasicConfigurator.configure();
            
        
        super.init(config);
    


uploadServlet

package top.sehnsucht;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import top.sehnsucht.utils.ExcelUtil;

import以上是关于jsp使用webuploader上传excel mysql导入导出 apache-POI的主要内容,如果未能解决你的问题,请参考以下文章

jsp利用webuploader实现超大文件分片上传断点续传

JSP+SpringMVC框架使用WebUploader插件实现注册时候头像图片的异步上传功能

jsp WebUploader 分块上传

jsp WebUploader 分块上传

使用WebUploader和servlet实现文件上传

js WebUploader 分块上传