用JDBC把Excel中的数据导入到Mysql数据库中

步骤: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:

 1 package FileUtil;
 2 
 3 import java.io.File;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 
 7 public class Util {
 8 
 9     private static String[] filepathofall = new String[1000000];
10     private static int k = 0; //k为文件总数
11     
12     private static boolean matchType(File file, String fileTypes) {
13         boolean rt = false;
14         String fExtName = file.getPath();
15         int i = fExtName.lastIndexOf('.');
16         if (i >= 0) {
17             fExtName = fExtName.substring(i);
18             fExtName = fExtName.toLowerCase();
19             i = fileTypes.indexOf(fExtName);
20             if (i >= 0)
21                 if (i + fExtName.length() >= fileTypes.length() || fileTypes.charAt(i + fExtName.length()) == ',')
22                     rt = true;
23         }
24         return rt;
25     }
26 
27     public static String[] fileList(String filepath, String fileTypes) throws FileNotFoundException, IOException {
28         File file = new File(filepath);
29         if (!file.isDirectory()) {
30             if (matchType(file, fileTypes)) {
31                 System.out.println("absolutepath=" + file.getAbsolutePath());
32             }
33         } else if (file.isDirectory()) {
34             String[] filelist = file.list();
35             for (int i = 0; i < filelist.length; i++) {
36                 File readfile = new File(filepath + "\" + filelist[i]);
37                 if (!readfile.isDirectory()) {
38                     if (matchType(readfile, fileTypes)) {
39                         //System.out.println("absolutepath=" + readfile.getAbsolutePath());
40                         filepathofall[k++] = readfile.getAbsolutePath();
41                     }
42                 } else if (readfile.isDirectory()) {
43                     fileList(filepath + "/" + filelist[i], fileTypes);
44                 }
45             }
46         }
47         return filepathofall;
48     }
49 }

ImportDataFromExcelToMysql.java:

  1 package ImportData;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.util.Date;
  8 import java.util.HashMap;
  9 import java.util.Map;
 10 
 11 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 12 import org.apache.poi.ss.usermodel.Cell;
 13 import org.apache.poi.ss.usermodel.DateUtil;
 14 import org.apache.poi.ss.usermodel.Row;
 15 import org.apache.poi.ss.usermodel.Sheet;
 16 import org.apache.poi.ss.usermodel.Workbook;
 17 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 18 import org.slf4j.Logger;
 19 import org.slf4j.LoggerFactory;
 20 
 21 import FileUtil.Util;
 22 
 23 import com.mysql.jdbc.Connection;
 24 import java.sql.*;
 25 
 26 public class ImportDataFromExcelToMysql {
 27     private Logger logger = LoggerFactory.getLogger(ImportDataFromExcelToMysql.class);
 28     private Workbook wb;
 29     private Sheet sheet;
 30     private Row row;
 31     private static String[] filepathlist;    //文件名列表
 32     private static boolean titleflag = false;//判断标题是否为数据
 33     
 34     public ImportDataFromExcelToMysql(String filepath) {
 35         if (filepath == null) {
 36             return;
 37         }
 38         String ext = filepath.substring(filepath.lastIndexOf("."));//获取文件格式
 39         try {
 40             InputStream is = new FileInputStream(filepath);
 41             if (".xls".equals(ext)) {
 42                 wb = new HSSFWorkbook(is);
 43             } else if (".xlsx".equals(ext)) {
 44                 wb = new XSSFWorkbook(is);
 45             } else {
 46                 wb = null;
 47             }
 48         } catch (FileNotFoundException e) {
 49             logger.error("FileNotFoundException", e);
 50         } catch (IOException e) {
 51             logger.error("IOException", e);
 52         }
 53     }
 54 
 55     /**
 56      * 读取Excel表格表头的内容
 57      */
 58     public String[] readExcelTitle() throws Exception {
 59         titleflag = false;
 60         if (wb == null) {
 61             throw new Exception("Workbook对象为空!");
 62         }
 63         
 64         sheet = wb.getSheetAt(0);
 65         row = sheet.getRow(0);
 66         
 67         // 标题总列数
 68         int colNum = row.getPhysicalNumberOfCells();
 69         System.out.println(colNum);
 70         String[] title = new String[colNum];
 71         for (int i = 0; i < colNum; i++) {
 72             //title[i] = getStringCellValue(row.getCell((short) i));
 73             title[i] = getCellFormatValue(row.getCell(i)).toString();
 74         }
 75         
 76         //判断title第一个字段是否为数字,即可知道title是否为数据
 77         Cell cell = row.getCell(0);
 78         switch (cell.getCellTypeEnum()){//.getCellType()) {
 79         case NUMERIC:
 80         case FORMULA: {
 81             // 判断当前的cell是否为Date
 82             if (DateUtil.isCellDateFormatted(cell)) {
 83                 titleflag = false;
 84             } else {// 如果是纯数字
 85                 titleflag = true;
 86             }
 87             break;
 88         }
 89         case STRING:// 如果当前Cell的Type为STRING
 90             titleflag = false;
 91             break;
 92         default:// 默认的Cell值
 93             titleflag = false;
 94         }
 95         
 96         return title;
 97     }
 98 
 99     /**
100      * 读取Excel数据内容
101      */
102     public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
103         if (wb == null) {
104             throw new Exception("Workbook对象为空!");
105         }
106         Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();
107 
108         sheet = wb.getSheetAt(0);
109         // 得到总行数
110         int rowNum = sheet.getLastRowNum();
111         row = sheet.getRow(0);
112         int colNum = row.getPhysicalNumberOfCells();
113         // 正文内容应该从第二行开始,第一行为表头的标题
114         for (int i = 1; i <= rowNum; i++) {
115             row = sheet.getRow(i);
116             int j = 0;
117             Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
118             while (j < colNum) {
119                 Object obj = getCellFormatValue(row.getCell(j));
120                 cellValue.put(j, obj);
121                 j++;
122             }
123             content.put(i, cellValue);
124         }
125         return content;
126     }
127 
128     /**
129      * 根据Cell类型设置数据
130      */
131     private Object getCellFormatValue(Cell cell) {
132         Object cellvalue = "";
133         if (cell != null) {
134             // 判断当前Cell的Type
135             switch (cell.getCellTypeEnum()){//.getCellType()) {
136             case NUMERIC:
137             case FORMULA: {
138                 // 判断当前的cell是否为Date
139                 if (DateUtil.isCellDateFormatted(cell)) {
140                     // 如果是Date类型则,转化为Data格式
141                     // data格式是带时分秒的:2013-7-10 0:00:00
142                     // cellvalue = cell.getDateCellValue().toLocaleString();
143                     // data格式是不带带时分秒的:2013-7-10
144                     Date date = cell.getDateCellValue();
145                     cellvalue = date;
146                 } else {// 如果是纯数字
147 
148                     // 取得当前Cell的数值
149                     cellvalue = String.valueOf((int)cell.getNumericCellValue());
150                 }
151                 break;
152             }
153             case STRING:// 如果当前Cell的Type为STRING
154                 // 取得当前的Cell字符串
155                 cellvalue = """+cell.getRichStringCellValue().getString()+""";
156                 //字符串加上双引号"",否则导入数据时会出错
157                 break;
158             default:// 默认的Cell值
159                 cellvalue = "";
160             }
161         } else {
162             cellvalue = "";
163         }
164         return cellvalue;
165     }
166 
167     public static void main(String[] args) {
168         try {            
169             //connection
170             Class.forName("com.mysql.jdbc.Driver");
171             String url = "jdbc:mysql://localhost:3306/wmj?&useSSL=false";  //设置url,wmj是database
172             Connection conn;//创建连接
173             conn = (Connection)DriverManager.getConnection(url, "root", "root123");//username="root",password = "root123"
174             Statement stmt = conn.createStatement();
175             
176             filepathlist = Util.fileList("D:\lzu\数据预处理\Data", ".xls,.xlsx");//导入数据文件夹和数据文件类型
177             
178             
179             
180             for(String filepath : filepathlist) {
181                 //插入数据前
182                 String t = "";
183                 String sql = "select count(*) from tbl_data_bak";
184                 ResultSet ret = stmt.executeQuery(sql);
185                 if(ret.next()) {
186                     System.out.print("count="+ret.getInt(1));
187                 }
188                 
189                 ImportDataFromExcelToMysql excelReader = new ImportDataFromExcelToMysql(filepath);
190                 // 对读取Excel表格标题测试
191                 String[] title = excelReader.readExcelTitle();
192                 //System.out.println("获得Excel表格的标题:");
193                 for (String s : title) {
194                     //System.out.print(s + "| ");
195                     t += s + ",";
196                 }
197                 t = t.substring(0,t.length()-1);
198                 //System.out.println("title = " + t);
199                 
200                 // 如果标题是数据,则插入
201                 if(titleflag) {
202                     sql = "insert into tbl_data_bak values(" + t + ");";
203                     stmt.executeUpdate(sql);
204                 }
205                 
206                 // 插入数据后
207                 sql = "select count(*) from tbl_data_bak";
208                 ret = stmt.executeQuery(sql);
209                 if(ret.next()) {
210                     System.out.print("count="+ret.getInt(1));
211                 }
212                 
213                 // 对读取Excel表格内容测试
214                 Map<Integer, Map<Integer, Object>> map = excelReader.readExcelContent();
215                 //System.out.println("获得Excel表格的内容:");
216                 for (int i = 1; i <= map.size(); i++) {
217                     //System.out.println(map.get(i));
218                     sql = map.get(i).values().toString().substring(1,map.get(i).values().toString().length()-1);
219                     //System.out.println("sql=" + sql);
220                     stmt.executeUpdate("insert into tbl_data_bak values("+sql+");");
221                 }
222                 
223                 // 插入数据后
224                 sql = "select count(*) from tbl_data_bak";
225                 ret = stmt.executeQuery(sql);
226                 if(ret.next()) {
227                     System.out.print("count="+ret.getInt(1));
228                 }
229             }
230             stmt.close();
231             conn.close();
232             }
233         /*catch(SQLException e) {
234             e.printStackTrace();
235         }*/
236         catch (FileNotFoundException e) {
237             System.out.println("未找到指定路径的文件!");
238             e.printStackTrace();
239         } catch (Exception e) {
240             e.printStackTrace();
241         }
242     }
243 }

最后。

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

 

原文地址:https://www.cnblogs.com/wmjtxt/p/8615472.html