步骤:0.在Mysql数据库中先建好table

1.从Excel表格读数据

2.用JDBC连接Mysql数据库

3.把读出的数据导入到Mysql数据库的相应表中

其中,步骤0的table我是先在Mysql数据库中建好的,也可以用JDBC连上数据库以后再建表;步骤1的代码是网上找的;其他部分都是我自己写的。

之前我自己写的部分还被误删了,后来又重新写了。所以就想把代码放到网上,也算做个备份。说不定以后有用呢。

前两天又想到可以把代码放到github上面,也不错。

这里呢,我就把代码一股脑全粘在这里(原谅我太懒)。

jar包:

除了mysql-connector-java-5.1.45-bin.jar,其他都是读取Excel数据用的。

然后是代码:

Util.java:

 package FileUtil;

 import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; public class Util { private static String[] filepathofall = new String[1000000];
private static int k = 0; //k为文件总数 private static boolean matchType(File file, String fileTypes) {
boolean rt = false;
String fExtName = file.getPath();
int i = fExtName.lastIndexOf('.');
if (i >= 0) {
fExtName = fExtName.substring(i);
fExtName = fExtName.toLowerCase();
i = fileTypes.indexOf(fExtName);
if (i >= 0)
if (i + fExtName.length() >= fileTypes.length() || fileTypes.charAt(i + fExtName.length()) == ',')
rt = true;
}
return rt;
} public static String[] fileList(String filepath, String fileTypes) throws FileNotFoundException, IOException {
File file = new File(filepath);
if (!file.isDirectory()) {
if (matchType(file, fileTypes)) {
System.out.println("absolutepath=" + file.getAbsolutePath());
}
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
if (matchType(readfile, fileTypes)) {
//System.out.println("absolutepath=" + readfile.getAbsolutePath());
filepathofall[k++] = readfile.getAbsolutePath();
}
} else if (readfile.isDirectory()) {
fileList(filepath + "/" + filelist[i], fileTypes);
}
}
}
return filepathofall;
}
}

ImportDataFromExcelToMysql.java:

 package ImportData;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import FileUtil.Util; import com.mysql.jdbc.Connection;
import java.sql.*; public class ImportDataFromExcelToMysql {
private Logger logger = LoggerFactory.getLogger(ImportDataFromExcelToMysql.class);
private Workbook wb;
private Sheet sheet;
private Row row;
private static String[] filepathlist; //文件名列表
private static boolean titleflag = false;//判断标题是否为数据 public ImportDataFromExcelToMysql(String filepath) {
if (filepath == null) {
return;
}
String ext = filepath.substring(filepath.lastIndexOf("."));//获取文件格式
try {
InputStream is = new FileInputStream(filepath);
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
} /**
* 读取Excel表格表头的内容
*/
public String[] readExcelTitle() throws Exception {
titleflag = false;
if (wb == null) {
throw new Exception("Workbook对象为空!");
} sheet = wb.getSheetAt(0);
row = sheet.getRow(0); // 标题总列数
int colNum = row.getPhysicalNumberOfCells();
System.out.println(colNum);
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
//title[i] = getStringCellValue(row.getCell((short) i));
title[i] = getCellFormatValue(row.getCell(i)).toString();
} //判断title第一个字段是否为数字,即可知道title是否为数据
Cell cell = row.getCell(0);
switch (cell.getCellTypeEnum()){//.getCellType()) {
case NUMERIC:
case FORMULA: {
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell)) {
titleflag = false;
} else {// 如果是纯数字
titleflag = true;
}
break;
}
case STRING:// 如果当前Cell的Type为STRING
titleflag = false;
break;
default:// 默认的Cell值
titleflag = false;
} return title;
} /**
* 读取Excel数据内容
*/
public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
if (wb == null) {
throw new Exception("Workbook对象为空!");
}
Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>(); sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
Object obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
} /**
* 根据Cell类型设置数据
*/
private Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
// 判断当前Cell的Type
switch (cell.getCellTypeEnum()){//.getCellType()) {
case NUMERIC:
case FORMULA: {
// 判断当前的cell是否为Date
if (DateUtil.isCellDateFormatted(cell)) {
// 如果是Date类型则,转化为Data格式
// data格式是带时分秒的:2013-7-10 0:00:00
// cellvalue = cell.getDateCellValue().toLocaleString();
// data格式是不带带时分秒的:2013-7-10
Date date = cell.getDateCellValue();
cellvalue = date;
} else {// 如果是纯数字 // 取得当前Cell的数值
cellvalue = String.valueOf((int)cell.getNumericCellValue());
}
break;
}
case STRING:// 如果当前Cell的Type为STRING
// 取得当前的Cell字符串
cellvalue = "\""+cell.getRichStringCellValue().getString()+"\"";
//字符串加上双引号"",否则导入数据时会出错
break;
default:// 默认的Cell值
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
} public static void main(String[] args) {
try {
//connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/wmj?&useSSL=false"; //设置url,wmj是database
Connection conn;//创建连接
conn = (Connection)DriverManager.getConnection(url, "root", "root123");//username="root",password = "root123"
Statement stmt = conn.createStatement(); filepathlist = Util.fileList("D:\\lzu\\数据预处理\\Data", ".xls,.xlsx");//导入数据文件夹和数据文件类型 for(String filepath : filepathlist) {
//插入数据前
String t = "";
String sql = "select count(*) from tbl_data_bak";
ResultSet ret = stmt.executeQuery(sql);
if(ret.next()) {
System.out.print("count="+ret.getInt(1));
} ImportDataFromExcelToMysql excelReader = new ImportDataFromExcelToMysql(filepath);
// 对读取Excel表格标题测试
String[] title = excelReader.readExcelTitle();
//System.out.println("获得Excel表格的标题:");
for (String s : title) {
//System.out.print(s + "| ");
t += s + ",";
}
t = t.substring(0,t.length()-1);
//System.out.println("title = " + t); // 如果标题是数据,则插入
if(titleflag) {
sql = "insert into tbl_data_bak values(" + t + ");";
stmt.executeUpdate(sql);
} // 插入数据后
sql = "select count(*) from tbl_data_bak";
ret = stmt.executeQuery(sql);
if(ret.next()) {
System.out.print("count="+ret.getInt(1));
} // 对读取Excel表格内容测试
Map<Integer, Map<Integer, Object>> map = excelReader.readExcelContent();
//System.out.println("获得Excel表格的内容:");
for (int i = 1; i <= map.size(); i++) {
//System.out.println(map.get(i));
sql = map.get(i).values().toString().substring(1,map.get(i).values().toString().length()-1);
//System.out.println("sql=" + sql);
stmt.executeUpdate("insert into tbl_data_bak values("+sql+");");
} // 插入数据后
sql = "select count(*) from tbl_data_bak";
ret = stmt.executeQuery(sql);
if(ret.next()) {
System.out.print("count="+ret.getInt(1));
}
}
stmt.close();
conn.close();
}
/*catch(SQLException e) {
e.printStackTrace();
}*/
catch (FileNotFoundException e) {
System.out.println("未找到指定路径的文件!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

最后。

写这个东西之前,我没有接触过Java,用了以后才发现Java也蛮好用的,所以自己又学了学。发现想学好还是很难的,东西很多。上学期我还学了点Python,然而都是皮毛而已。真是接触的越多,发现自己会的越少。加油吧。

用JDBC把Excel中的数据导入到Mysql数据库中的更多相关文章

  1. 用ttBulkCp把excel中的数据导入到timesten数据库中

    最近要做数据预处理,需要用到数据库.而且是以前从来没听说过的TimesTen. 首要目标是要把Excel里的数据,导入到TimesTen数据库中.而TimesTen在win10里用不了,于是我就在虚拟 ...

  2. c#.net Excel中的数据导入到SQL数据库中

    /// <summary>        /// 从Excel 导入学生        /// </summary>        /// <param name=&qu ...

  3. 如何用java POI将word中的内容导入到mysql数据库中

    由于作业需要,要求我们将word文档中的数据直接导入到mysql中,在网上找了很常时间,终于将其解决. 由于比较初级,所以处理的word文档是那种比较规范的那种,条例比较清晰,设计的思路也比较简单,就 ...

  4. Oracle中的数据迁移到Mysql数据库中的方式Navicat premium工具

    1.安装 Navicat premium工具 2.破解 Navicat premium工具 3.连接需要相互迁移的两个库Mysql和Oracle(可以是远程的或者本机的数据库都是可以的) 4.连接上之 ...

  5. 把excel中的数据导入到Oracle数据库中

    从事工作以来,数据库一直使用oracle,却不知道excel导入oracle,今天看了一篇文章,分享给大家,希望对大家有用. https://jingyan.baidu.com/article/0f5 ...

  6. 如何将MongoDB数据库的数据迁移到MySQL数据库中

    FAQ v2.0终于上线了,断断续续忙了有2个多月.这个项目是我实践的第一个全栈的项目,从需求(后期有产品经理介入)到架构,再到设计(有征询设计师的意见).构建(前端.后台.数据库.服务器部署),也是 ...

  7. 怎样把excel的数据导入到sqlserver2000数据库中

    在做程序的时候有时需要把excel数据导入到sqlserver2000中,以前没从外部导入过数据,今天刚做了一下导入数据,感觉还是蛮简单的,没做过之前还想着多么的复杂呢,下面就来分享一下我是如何把ex ...

  8. 使用Python将Excel中的数据导入到MySQL

    使用Python将Excel中的数据导入到MySQL 工具 Python 2.7 xlrd MySQLdb 安装 Python 对于不同的系统安装方式不同,Windows平台有exe安装包,Ubunt ...

  9. python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图

    python制作简单excel统计报表3之将mysql数据库中的数据导入excel模板并生成统计图 # coding=utf-8 from openpyxl import load_workbook ...

随机推荐

  1. 两个div不同高度并排显示

    在HTML中让两个div并排显示,通常情况下有三种实现方式,包括: (1)设置为行内样式,display:inline-block (2)设置float浮动 (3)设置position定位属性为abs ...

  2. Message高级特性 & 内嵌Jetty实现文件服务器

    1. Messaage Properties  常见属性 更多的属性以及介绍参考:http://activemq.apache.org/activemq-message-properties.html ...

  3. # 20175333曹雅坤《Java程序设计》第五周学习总结

    教材学习内容总结 第六章要点: 1.接口:1)接口声明: interface //接口的名字 2)接口体 2.实现接口:类实现接口:一个类需要在类声明中使用关键字implements声明该类实现一个或 ...

  4. golang interface类型转string等其他类型

    inter 是interface类型,转化为string类型是: str := inter .(string) 转为其他类型也类似

  5. L2-007 家庭房产 (25 分) (并查集)

    链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805068539215872 题目: 给定每个人的家庭成员和其自己名 ...

  6. Qt+mpg123+openal播放MP3流

    #ifndef PLAYSTREAM_H #define PLAYSTREAM_H #include <QObject> #include "../libMPG123/mpg12 ...

  7. 网络流板子/费用流板子 2018南京I题+2016青岛G题

    2018南京I题: dinic,链式前向星,数组队列,当前弧优化,不memset全部数组,抛弃满流点,bfs只找一条增广路,每次多路增广 #include <bits/stdc++.h> ...

  8. 【easy】437. Path Sum III 二叉树任意起始区间和

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  9. zabbix3.2自动发现批量监控redis端口状态

    使用nmap提示被防火墙阻挡,实际没有启用防火墙 [root@eus_chinasoft_haproxy:/usr/local/aegis]# nmap 172.20.103.202 -p 7000 ...

  10. git(windows)

    windows下比较比较好用的git客户端: 1. msysgit + TortoiseGit(乌龟git) 2. GitHub for Windows 3. Git Extensions