java 读取Excel表格并用jdbc连接mysql导入数据到对应表

邓业
2023-12-01

简单使用jdbc连接mysql导入excel表格内容到指定表中

首先是读取excel表格的函数代码:

//这里是对单个sheet读取,多sheet可以对下面函数修改成循环读取sheet
public Map<Integer, Map<String, String>> readExcel() {
			File file = new File("/root/表1.xlsx");  //excel路径
			Map<Integer, Map<String, String>> mapRow = new HashMap<Integer, Map<String, String>>();
			try {
				XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));  //.xlsx文件
				//HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));//.xls文件
				Sheet sheet = workbook.getSheet("sheet1");
				for (Row row : sheet) {
					Map<String, String> mapColumn = new HashMap<String, String>();
					for (Cell cell : row) {
						int type = cell.getCellType();
						String cellContext = "";
						switch (type) { // 判断数据类型
						case Cell.CELL_TYPE_BLANK:// 空的
							cellContext = "";
							break;
						case Cell.CELL_TYPE_BOOLEAN:// 布尔
							cellContext = cell.getBooleanCellValue() + "";
							break;
						case Cell.CELL_TYPE_ERROR:// 错误
							cellContext = cell.getErrorCellValue() + "";
							break;
						case Cell.CELL_TYPE_FORMULA:// 公式
							cellContext = cell.getCellFormula();
							break;
						case Cell.CELL_TYPE_NUMERIC:// 数字或日期
							if (HSSFDateUtil.isCellDateFormatted(cell)) {
								cellContext = new DataFormatter().formatRawCellContents(cell.getNumericCellValue(), 0, "yyyy-mm-dd");// 格式化日期
							} else {
								NumberFormat nf = NumberFormat.getInstance();
								nf.setGroupingUsed(false);
								cellContext = nf.format(cell.getNumericCellValue());
							}
							break;
						case Cell.CELL_TYPE_STRING:// 字符串
							cellContext = cell.getStringCellValue();
							break;
						default:
							break;
						}
						mapColumn.put(sheet.getRow(0).getCell(cell.getColumnIndex()).toString(), cellContext);
					}
					mapRow.put( row.getRowNum(), mapColumn);
					//System.out.print(mapRow);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return mapRow;
		}

接下来用jdbc连接数据库,先提供一个jdbc连接数据库工具类
private static class DBConnectionUtil {
		private static final String URL = "jdbc:mysql://localhost:3306/[数据库名]?rewriteBatchedStatements=true&autoReconnect=true&allowMultiQueries=true&useSSL=false&serverTimezone=CST&allowPublicKeyRetrieval=true";
		private static final String USERNAME = "root";
		private static final String PASSWORD = "root";
		private static final String DRIVER_CLASSNAME = "com.mysql.cj.jdbc.Driver";

		static {
			// 1、加载驱动
			try {
				Class.forName(DRIVER_CLASSNAME);
			} catch (ClassNotFoundException e) {
			}
		}

		/**
		 * 返回一个Connection连接
		 */
		static Connection getConnection() {
			Connection conn = null;
			// 2、连接数据库
			try {
				conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
			} catch (SQLException e) {
			}
			return conn;
		}

		/**
		 * 关闭Connection,Statement连接
		 */
		public static void close(Connection conn, Statement stmt) {
			try {
				conn.close();
				stmt.close();
			} catch (SQLException e) {
			}
		}

		/**
		 * 关闭Connection,Statement,ResultSet连接
		 */
		public static void close(Connection conn, Statement stmt, ResultSet rs) {
			try {
				close(conn, stmt);
				rs.close();
			} catch (SQLException e) {
			}
		}

	}

下面是具体读取连接导入:

public void modifyTable() throws SQLException {			
			Connection conn = DBConnectionUtil.getConnection();  //调用上面java工具类,创建连接
			Statement ps = conn.createStatement();
			Map<Integer, Map<String, String>> map = readExcel();  //读取表格
			//开始对sheet的每一行数据进行循环操作	
			 for (Map.Entry<Integer, Map<String, String>> entry : map.entrySet()) {
				 Map<String, String> maprow =entry.getValue();			 
				 String name = maprow.get("随便一个列名");
				 if( "与上面的列名同".equals(name))  continue;	 //因为读取到的第一行是各列的名称,不是数据,跳过				 
				  ps.addBatch("这里是要对当前行数据操作的SQL");	//maprow.get("列名")	可以得到当前行的具体列的值	
				  ps.addBatch("这里是要对当前行数据操作的SQL");	   //addBatch() 执行多条sql 如//"INSERT INTO tablename(字段1,字段2,字段3)  VALUES('"+maprow.get("列名")+"','"+maprow.get("列名")+"','"+maprow.get("列名")+"')"
				 ps.executeBatch();	                      		
				   
			 }  
			 System.out.println("**************西风吹老洞庭波,一夜湘君白发多;醉后不知天在水,满船清梦压星河**********************");
			 DBConnectionUtil.close(conn, ps);
		}

好了,以上就是一个简单地java读取excel表格数据,jdbc存入数据库表的函数

 类似资料: