Java 文件上传 读取excel数据导入MySQL

Java代码 专栏收录该内容
25 篇文章 0 订阅

    本文描述一种获取excel中数据,并保存数据库的方法,其实现的主要功能为:将excel上传服务器,得到该excel的绝对地址,解析excel中的内容,获取到行与列的内容,保存到mysql数据库。

    为实现该功能主要有两种方式:

    (1)使用ajax异步上传。

    (2)使用form表单提交。

   在第(1)中方法中,通过如下代码获取file文件的路径时,会遇到如下图中的隐藏式的路径,该路径并无法实现上传文件。

var file = document.getElementById("file").value;

    针对上述问题,笔者查阅了相当多的解决方法,但是未能解决,始终无法获取真实的绝对路径,从而无法实现上传文件,因为读者若执着使用该方法,可能会花费大量时间,且无法解决,若有人解决请在评论区加以解释,不胜感激!!!

    因此在本文中,主要陈述第(2)种方法实现获取excel数据存入MySQL的方法。

    本文中excel中主要存储的数据如下图所示(测试数据)。

    技术路线如下:

    获取excel文件(form提交)-------->上传服务器--------->获取excel文件在服务器的路劲-------->读取excel数据--------->存入MySQL

    实现代码如下:
    页面上传jsp代码:

<form action="${pageContext.request.contextPath}/UploadFile" enctype="multipart/form-data" method="post">  
        上传文件:<input type="file" name="file2"><br/>
           <input type="submit" value="提交"/>
    </form>

    获取页面数据的servlet,名称为UploadFile,其主要代码如下:

package com.njau.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.njau.dao.ExcelOperate;
import com.njau.dao.QikanDao;
import com.njau.po.Qikan;


public class UploadFile extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	private static final long serialVersionUID = 1L;
	final static String uploadAddres = System.getProperty("catalina.home")+"\\webapps\\Science\\uploadFile\\";
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
        //上传服务器部分
		String fileName = null;
			//1、创建一个DiskFileItemFactory工厂
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        //2、创建一个文件上传解析器
	        ServletFileUpload upload = new ServletFileUpload(factory);
	        //解决上传文件名的中文乱码
	        upload.setHeaderEncoding("UTF-8"); 
			factory.setSizeThreshold(1024 * 500);//设置内存的临界值为500K
			File linshi = new File("E:\\linshi");//当超过500K的时候,存到一个临时文件夹中
			factory.setRepository(linshi);
			upload.setSizeMax(1024 * 1024 * 5);//设置上传的文件总的大小不能超过5M
			try {
				// 1. 得到 FileItem 的集合 items
				List<FileItem> /* FileItem */items = upload.parseRequest(request);
	 
				// 2. 遍历 items:
				for (FileItem item : items) {
					// 若是一个一般的表单域, 打印信息
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString("utf-8");
	 
						System.out.println(name + ": " + value);
						
						
					}
					// 若是文件域则把文件保存到 e:\\files 目录下.
					else {
						fileName = item.getName();
						long sizeInBytes = item.getSize();
						//System.out.println(fileName);
						//System.out.println(sizeInBytes);
	 
						InputStream in = item.getInputStream();
						byte[] buffer = new byte[1024];
						int len = 0;
	 
						fileName = uploadAddres + fileName;//文件最终上传的位置
						System.out.println(fileName);
						OutputStream out = new FileOutputStream(fileName);
	 
						while ((len = in.read(buffer)) != -1) {
							out.write(buffer, 0, len);
						}
	 
						out.close();
						in.close();
					}
				}
	 
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
        //解析excel,并存入数据库部分
		File file = new File(fileName);//获取excel文件
		ExcelOperate eo = new ExcelOperate();
	       String[][] result = eo.getData(file, 1);//调用解析方法,存入二维数组result

	       int rowLength = result.length;

	       for(int i=0;i<rowLength;i++) {

	           for(int j=0;j<result[i].length;j++) {
	 
	              //System.out.print(result[i][j]+"\t\t");//打印excel文件中数据
	              Qikan qk = new Qikan();
	              qk.setName(result[i][1]);
				  qk.setFangxiang(result[i][0]);
				  qk.setSx(result[i][2]);
				  qk.setLink(result[i][3]);
				  int type = QikanDao.getMark(qk);//检查数据库中是否以存在需上传数据
				 // System.out.println(type);
				  if(type==0){
					  QikanDao.saveQikan(qk);//存入MySQL数据库
				  }
				  
				  break;//跳出循环
	           }

	           System.out.println();

	       }
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		doGet(request, response);

	}

}

    Java获取excel数据代码,名称为ExcelOperate,即上述servlet中调用的getData()方法,具体实现代码如下:

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


public class ExcelOperate {

    public static void main(String[] args) throws Exception {
        File file = new File("D:\\guide.csv");
        String[][] result = getData(file, 1);
        int rowLength = result.length;
        for (int i = 0; i < rowLength; i++) {
            System.out.println(result[i]);
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j] + "\t\t");
            }
            System.out.println();
        }
    }

    /**
     * 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
     *
     * @param file       读取数据的源Excel
     * @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
     * @return 读出的Excel中数据的内容
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String[][] getData(File file, int ignoreRows)
            throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        int rowSize = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                file));
        // 打开HSSFWorkbook
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            HSSFSheet st = wb.getSheetAt(sheetIndex);
            // 第一行为标题,不取
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
                HSSFRow row = st.getRow(rowIndex);
                if (row == null) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);
                    if (cell != null) {
                        // 注意:一定要设成这个,否则可能会出现乱码,后面版本默认设置
                        //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    Date date = cell.getDateCellValue();
                                    if (date != null) {
                                        value = new SimpleDateFormat("yyyy-MM-dd")
                                                .format(date);
                                    } else {
                                        value = "";
                                    }
                                } else {
                                    value = new DecimalFormat("0").format(cell

                                            .getNumericCellValue());
                                }
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                // 导入时如果为公式生成的数据则无值
                                if (!cell.getStringCellValue().equals("")) {
                                    value = cell.getStringCellValue();
                                } else {
                                    value = cell.getNumericCellValue() + "";
                                }
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value = "";
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                value = (cell.getBooleanCellValue() == true ? "Y"

                                        : "N");
                                break;
                            default:
                                value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                }
                if (hasValue) {
                    result.add(values);
                }
            }
        }
        in.close();
        String[][] returnArray = new String[result.size()][rowSize];
        for (int i = 0; i < returnArray.length; i++) {
            returnArray[i] = (String[]) result.get(i);
        }
        return returnArray;
    }


    /**
     * 去掉字符串右边的空格
     *
     * @param str 要处理的字符串
     * @return 处理后的字符串
     */

    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (str.charAt(i) != 0x20) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }
}

    Java,检查数据库中是否已存在需上传数据,调用函数名为getMark()方法,代码如下所示:

public static int getMark(Qikan qk) {
		int mark = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Connection conn = null;
		String name = qk.getName();
		String sql="select name from qk where name='"+name+"'";//��ѯ���?
		try {
			conn = DB.getConn();
			pstmt = DB.getPStmt(conn, sql);
			rs = pstmt.executeQuery();
			if(rs.next()){
				mark=1;
			}
	}catch (SQLException e) {
		e.printStackTrace();
	} finally {
		DB.closeRs(rs);
		DB.closeStmt(pstmt);
		DB.closeConn(conn);
	}
	return mark;
	}
}

    存入MySQL数据库代码如下:

public static void saveQikan(Qikan qk) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			conn = DB.getConn();
			String sql = "insert into qk value (?,?,?,?,?) "; 
			pstmt = DB.getPStmt(conn, sql);
			pstmt.setObject(1, null);
			pstmt.setString(2, qk.getFangxiang());
			pstmt.setString(3, qk.getName());
			pstmt.setString(4, qk.getSx());
			pstmt.setString(5, qk.getLink());
			
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DB.closeStmt(pstmt);
			DB.closeConn(conn);
		}
		
	}

注:文中使用jdbc方法访问数据库,具体的工具类如下:

package com.njau.common;

import java.sql.*;


public class DB {
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");//锟斤拷锟斤拷锟斤拷菘锟斤拷锟斤拷锟斤拷Class.forName(锟斤拷锟斤拷锟斤拷锟�
		} catch (ClassNotFoundException e) {
			e.printStackTrace();//锟斤拷锟斤拷撇锟斤拷锟斤拷诨锟斤拷锟斤拷锟矫伙拷屑锟斤拷锟�
		}
	}

	private DB() {
	}

	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/sciencenew?useUnicode=true&characterEncoding=utf-8", "root", "123456");//通锟斤拷锟矫伙拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷拥锟街凤拷锟饺★拷锟捷匡拷锟斤拷锟接讹拷锟斤拷DriverManager.getConnection(锟斤拷锟接碉拷址,锟矫伙拷锟斤拷,锟斤拷锟斤拷)
		} catch (SQLException e) {
			e.printStackTrace();//锟斤拷莸锟街凤拷锟斤拷锟斤拷锟斤拷锟矫伙拷锟斤拷锟斤拷锟斤拷写锟斤拷
		}
		return conn;
	}

	public static void closeConn(Connection conn) {//锟截憋拷锟斤拷锟斤拷菘锟斤拷锟斤拷锟斤拷
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static Statement getStmt(Connection conn) {
		Statement stmt = null;
		try {
			stmt = conn.createStatement();//锟斤拷锟斤拷Statement实锟斤拷,Statement stmt = conn.createStatement()锟斤拷Statement锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷SQL锟斤拷锟斤拷锟斤拷锟藉,锟斤拷为Java锟斤拷锟斤拷锟睫凤拷锟斤拷锟斤拷锟斤拷要锟斤拷锟斤拷锟斤拷菘锟斤拷锟斤拷锟斤拷锟斤拷锟�
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}

	public static PreparedStatement getPStmt(Connection conn, String sql) {//使锟斤拷PreparedStatement实锟斤拷锟斤拷删锟侥诧拷
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}

	public static void closeStmt(Statement stmt) {
		try {
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public static ResultSet executeQuery(Statement stmt, String sql) {//执锟叫诧拷询SQL锟斤拷洌拷锟斤拷锟斤拷亟锟斤拷ResultSet rs = stmt.executeQuery(sql)
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public static void closeRs(ResultSet rs) {//锟截憋拷锟斤拷锟接o拷rs.close()锟斤拷stmt.close()锟斤拷conn.close()
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static ResultSet executeQuery(Connection conn, String sql) {
		ResultSet rs = null;
		try {
			rs = conn.createStatement().executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

}

参考https://www.cnblogs.com/winner-0715/p/6690094.html

  • 5
    点赞
  • 0
    评论
  • 26
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值