Java读取excel文件(.xlsx/.xls)和.csv文件存入MySQL数据库

  1 package com.reliable.service;
  2 
  3 import com.csvreader.CsvReader;
  4 import com.reliable.bean.FileDict;
  5 import com.reliable.dao.ReadFile;
  6 import com.reliable.util.JDBCUtil;
  7 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  8 import org.apache.poi.ss.usermodel.Cell;
  9 import org.apache.poi.ss.usermodel.Row;
 10 import org.apache.poi.ss.usermodel.Sheet;
 11 import org.apache.poi.ss.usermodel.Workbook;
 12 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 13 
 14 import java.io.*;
 15 import java.nio.charset.Charset;
 16 import java.sql.Connection;
 17 import java.sql.PreparedStatement;
 18 import java.sql.SQLException;
 19 import java.util.ArrayList;
 20 
 21 public class ReadFileImpl implements ReadFile {
 22     private int MAX_CELL_NUM;        //文件中最长的一行具有的单元格数
 23     private PreparedStatement preparedStatement=null;
 24     private Connection conn =null;
 25     //--------------------------------------------------
 26     public ArrayList<ArrayList<String>> readExcelFile(String path) throws IOException, SQLException {
 27         System.out.println("excel文件路径:"+path);       //输出文件路径
 28         ArrayList<String> tableName = new ArrayList<String>();
 29         String tableName_1="";                                      //备份表名
 30         String tableName_2="";                                      //操作表名
 31         ArrayList<ArrayList<String>> tableValue = new ArrayList<ArrayList<String>>();  //数据表的值
 32         File excel=new File(path);
 33         String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!
 34         System.out.println(split[0]+" "+split[1]);
 35         tableName_1=split[0];               //给备份数据表名赋值
 36         tableName_2=split[0]+"_"+split[1];      //给操作表名赋值
 37         System.out.println("备份表名:" + tableName_1);
 38         System.out.println("操作表名: " + tableName_2);
 39         tableName.add(tableName_1);
 40         tableName.add(tableName_2);
 41         tableValue.add(tableName);
 42         Workbook wb;                                                //新建文件
 43         FileInputStream fileStream = new FileInputStream(excel);   //文件流对象
 44         //根据文件后缀(xls/xlsx)进行判断
 45         if ("xls".equals(split[1])){
 46             //xls文件
 47             wb = new HSSFWorkbook(fileStream);
 48         }else{
 49             //xlsx文件
 50             wb = new XSSFWorkbook(fileStream);
 51         }
 52         //开始解析
 53         Sheet sheet = wb.getSheetAt(0);     //读取sheet 0
 54         MAX_CELL_NUM=getMaxCellNumExcel(sheet);
 55         int firstRowIndex = sheet.getFirstRowNum();   //获取第一行索引
 56         int lastRowIndex = sheet.getLastRowNum();     //获取最后一行索引
 57         for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
 58             Row row = sheet.getRow(rIndex);         //获取行索引
 59             ArrayList<String> tempTableValue = new ArrayList<String>();     //暂存一行的值,之后放到tableValue
 60             if (row != null) {
 61                 int lastCellIndex = MAX_CELL_NUM;                           //行的最后一个单元格
 62                 for (int cIndex = 0; cIndex < lastCellIndex; cIndex++) {   //遍历列(单元格)
 63                     Cell cell = row.getCell(cIndex,Row.RETURN_BLANK_AS_NULL);   //允许读空的单元格
 64                     if ((cell == null)) {
 65                         tempTableValue.add("NULL");
 66                     }else {
 67                         cell.setCellType(Cell.CELL_TYPE_STRING);                //转换单元格数据格式为String
 68                         tempTableValue.add(cell.getStringCellValue());
 69                     }
 70                 }
 71                 tableValue.add(tempTableValue);
 72             }
 73         }
 74         System.out.println("读出Excel文件的数据: "+tableValue);         //输出表格的所有值
 75         wb.close();
 76         //---------------------------------------------------------------------
 77         return tableValue;
 78     }
 79     //读CSV文件
 80     public ArrayList<ArrayList<String>> readCsvFile(String path) throws SQLException, IOException {
 81         System.out.println("CSV文件的路径: "+path);
 82         //首先判断编码格式
 83         String code=new String();
 84         ArrayList<ArrayList<String>> WrongData=new ArrayList<ArrayList<String>>();
 85         ArrayList<String> tableField = new ArrayList<String>();         //数据表字段名
 86         ArrayList<ArrayList<String>> tableValue = new ArrayList<ArrayList<String>>();  //数据表的值
 87         String tableName_1="";                                      //备份表名
 88         String tableName_2="";                                      //操作表名
 89         ArrayList<String> tableName = new ArrayList<String>();         //存放两个表名
 90         File file = new File(path);
 91         InputStream in= new FileInputStream(file);
 92         byte[] b = new byte[3];
 93         in.read(b);
 94         in.close();
 95         if (b[0] == -17 && b[1] == -69 && b[2] == -65)
 96         {
 97             code="UTF-8";
 98             System.out.println(file.getName() + ":编码为UTF-8");
 99         }
100         else
101         {
102             code="GBK";
103             System.out.println(file.getName() + ":可能是GBK,也可能是其他编码");
104         }
105         try {
106             // 创建CSV读对象
107             CsvReader csvReader = new CsvReader(path,',', Charset.forName(code));
108             String[] split1 = path.split("\\.");  //.是特殊字符,需要转义!
109 //            System.out.println(split1[0]+" "+split1[1]);
110             String[] split2 = split1[0].split("\\\\");
111 //            System.out.println(split2[split2.length-1]);
112             tableName_1=split2[split2.length-1];
113             tableName_2=split2[split2.length-1]+"_"+split1[1];
114             System.out.println("备份表名:"+tableName_1);
115             System.out.println("操作表名:"+tableName_2);
116             tableName.add(tableName_1);
117             tableName.add(tableName_2);
118             tableValue.add(tableName);
119             WrongData.add(tableName);
120             int rIndex=0;
121             // 跳过表头
122 //            csvReader.readHeaders();
123             boolean flag=true;
124             while (csvReader.readRecord()){
125                 // 读一整行
126                 String resString="";
127                 resString = csvReader.getRawRecord();
128                 resString=resString.replace(","," , ");  //替换, 为,空格
129                 System.out.println(resString);
130                 if(flag==true){
131                     tableField.add(resString);
132                     tableValue.add(tableField);
133                     WrongData.add(tableField);
134                     flag=false;
135                     continue;       //存放表头数据
136                 }else{
137 
138                 }
139                 String[] resString_list=resString.split(",");
140                 String[] tableField_list=tableField.get(0).split(",");
141                 ArrayList<String> tempTableValue = new ArrayList<String>();     //暂存一行的值,之后放到tableValue
142                 if(resString_list.length != tableField_list.length){        //判断这一行的长度和第一行是否一样
143                     tempTableValue.add(resString);
144                     WrongData.add(tempTableValue);                          //如果不一样那就是错误数据
145                 }else {
146                     tempTableValue.add(resString);
147                     tableValue.add(tempTableValue);
148                 }
149                 rIndex++;
150             }
151         } catch (IOException e) {
152             e.printStackTrace();
153         }
154 
155         //name1,sex1,age1
156 //        System.out.println(tableValue.get(0).get(0));
157         if (WrongData.size()!=2){
158             System.out.println("CSV文件的错误数据: "+WrongData);
159             return WrongData;
160         }else {
161             System.out.println("CSV文件的数据: "+tableValue);
162             return tableValue;
163         }
164     }
165 
166     //--------------------------------------------------
167     //插入数据库 xls和xlsx文件
168     public void insertExcelTable(ArrayList<ArrayList<String>> tableValue){
169         conn=JDBCUtil.getConnection();
170         ArrayList<String> tableName = tableValue.get(0);
171         tableValue.remove(0);       //删除第一行的值,表头信息不需要插入数据库
172         tableValue.remove(0);       //再次删除掉字段值
173         for(int j=0;j<tableName.size();j++)
174         {
175             for (ArrayList<String> item1 : tableValue){
176                 String INSERT_TABLE_SQL="INSERT INTO "+tableName.get(j)+" VALUES(";
177                 String tempString=new String();         //组装SQL语句
178                 for (int i =0 ;i<item1.size();i++){
179                     if(i!=item1.size()-1){
180                         tempString=tempString+"\""+item1.get(i)+"\""+",";
181                     }
182                     else{
183                         tempString=tempString+"\""+item1.get(i)+"\"";
184                     }
185                 }
186                 INSERT_TABLE_SQL=INSERT_TABLE_SQL+tempString+");";
187                 System.out.println(INSERT_TABLE_SQL);
188                 try{
189                     preparedStatement= conn.prepareStatement(INSERT_TABLE_SQL);
190                     preparedStatement.executeUpdate();
191                     conn.setAutoCommit(false);
192                     conn.commit();
193                     System.out.println("\n");
194                 }catch(SQLException e){
195                     e.printStackTrace();
196                 }
197             }
198         }
199     }
200     public void insertCsvTable(ArrayList<ArrayList<String>> tableValue){
201         ArrayList<String> tableName = tableValue.get(0);
202         tableName=tableValue.get(0);
203         tableValue.remove(0);
204         tableValue.remove(0);
205         conn=JDBCUtil.getConnection();
206         System.out.println("数据表长度: " + tableValue.size());
207         //插入
208         for(int j=0;j<tableName.size();j++){
209             for (int i=0 ;i<tableValue.size();i++){
210                 String INSERT_TABLE_SQL="INSERT INTO "+tableName.get(j)+" VALUES( ";
211                 String tempString=new String();
212                 String[] tempValue={};
213                 tempValue=tableValue.get(i).get(0).split("\\,");
214 //            System.out.println(tempValue[tempValue.length-1]);
215                 for (int k=0 ; k<tempValue.length; k++)
216                 {
217                     if(k!=tempValue.length-1){
218                         tempString=tempString +"\"" +tempValue[k]+"\"" +",";
219                     }
220                     else{
221                         tempString=tempString+"\"" +tempValue[k]+"\"";
222                     }
223                 }
224                 INSERT_TABLE_SQL=INSERT_TABLE_SQL+tempString+");";
225                 System.out.println(INSERT_TABLE_SQL);
226                 try{
227                     preparedStatement= conn.prepareStatement(INSERT_TABLE_SQL);
228                     preparedStatement.executeUpdate();
229                     conn.setAutoCommit(false);
230                     conn.commit();
231                 }catch(SQLException e){
232                     e.printStackTrace();
233                 }finally{
234                     //关闭数据库连接
235                 }
236             }
237         }
238     }
239     //--------------------------------------------------
240     //获取excel表一行最大的单元格数目的方法
241     public int getMaxCellNumExcel(Sheet sheet){
242         int resNum=0;
243         int firstRowIndex = sheet.getFirstRowNum();   //获取第一行索引
244         int lastRowIndex = sheet.getLastRowNum();     //获取最后一行索引
245         for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
246             Row row = sheet.getRow(rIndex);         //获取行索引
247             if(row.getLastCellNum()>resNum){
248                 resNum=row.getLastCellNum();
249             }
250         }
251         return resNum;
252     }
253 
254     //在DictServlet中被调用,同时调用read文件的方法给这个方法传参数
255     @Override
256     public FileDict getExcelDict(ArrayList<ArrayList<String>> ExcelValue) {
257         //根据传过来的字段名建立数据字典
258         //描述默认 ""
259         ArrayList<String> fieldDescribe=new ArrayList<>();
260         //字段类型默认text
261         ArrayList<String> fieldType=new ArrayList<>();
262         //大小默认显示 256
263         ArrayList<String> fieldSize=new ArrayList<>();
264         //单位默认 ""
265         ArrayList<String> fieldUnit=new ArrayList<>();
266         fieldSize.add("256");
267         fieldType.add("text");
268         fieldDescribe.add("无");
269         fieldUnit.add("无");
270         FileDict fileDict = new FileDict();
271         fileDict.setFieldDescribe(fieldDescribe);
272         fileDict.setFieldType(fieldType);
273         fileDict.setFieldSize(fieldSize);
274         fileDict.setTableName(ExcelValue.get(0));
275         fileDict.setNewFieldName(ExcelValue.get(1));
276         fileDict.setFieldName(ExcelValue.get(1));
277         fileDict.setFieldUnit(fieldUnit);
278         return fileDict;
279     }
280     @Override
281     public FileDict getCsvDict(ArrayList<ArrayList<String>> CsvValue) {
282         FileDict fileDict = new FileDict();
283         String[] fieldNameList=CsvValue.get(1).get(0).split("\\,");
284         String[] newFieldNameList=CsvValue.get(1).get(0).split("\\,");
285         ArrayList<String> fieldName=new ArrayList<>();
286         ArrayList<String> newFieldName=new ArrayList<>();
287         for (int i = 0;i<fieldNameList.length;i++)
288         {
289             fieldName.add(fieldNameList[i]);
290         }
291         for (int i = 0;i<newFieldNameList.length;i++)
292         {
293             newFieldName.add(newFieldNameList[i]);
294         }
295         //描述默认 ""
296         ArrayList<String> fieldDescribe=new ArrayList<>();
297         //字段类型默认text
298         ArrayList<String> fieldType=new ArrayList<>();
299         //大小默认显示 256
300         ArrayList<String> fieldSize=new ArrayList<>();
301         //单位默认 ""
302         ArrayList<String> fieldUnit=new ArrayList<>();
303         fieldSize.add("256");
304         fieldType.add("text");
305         fieldDescribe.add("无");
306         fieldUnit.add("无");
307         fileDict.setFieldDescribe(fieldDescribe);
308         fileDict.setFieldType(fieldType);
309         fileDict.setFieldSize(fieldSize);
310         fileDict.setFieldName(fieldName);
311         fileDict.setNewFieldName(newFieldName);
312         fileDict.setTableName(CsvValue.get(0));
313         fileDict.setFieldUnit(fieldUnit);
314         return fileDict;
315     }
316 
317     @Override
318     public void createTable(ArrayList<String[]> tableInfo) {
319         //获取Sqlsession
320         String DROP_TABLE_1="";
321         String DROP_TABLE_2="";
322         String CREATE_TABLE_1_SQL="";
323         String CREATE_TABLE_2_SQL="";
324         DROP_TABLE_1="DROP TABLE IF EXISTS "+ tableInfo.get(0)[0] +";";
325         DROP_TABLE_2="DROP TABLE IF EXISTS "+tableInfo.get(0)[1] +";";
326         CREATE_TABLE_1_SQL="CREATE TABLE "+ tableInfo.get(0)[0] +"(" ;
327         CREATE_TABLE_2_SQL="CREATE TABLE "+ tableInfo.get(0)[1] +"(" ;
328         //生成备份表建表语句 (字段、描述、类型)
329         CREATE_TABLE_1_SQL=getTableSQL(CREATE_TABLE_1_SQL, tableInfo.get(1) , tableInfo.get(2),tableInfo.get(3),tableInfo.get(4));
330         //生成操作表建表语句
331         CREATE_TABLE_2_SQL=getTableSQL(CREATE_TABLE_2_SQL, tableInfo.get(1) , tableInfo.get(2),tableInfo.get(3),tableInfo.get(4));
332         System.out.println(CREATE_TABLE_1_SQL);
333         System.out.println(CREATE_TABLE_2_SQL);
334         try {
335             conn=JDBCUtil.getConnection();
336             preparedStatement = conn.prepareStatement(DROP_TABLE_1);
337             preparedStatement.executeUpdate();
338             preparedStatement= conn.prepareStatement(CREATE_TABLE_1_SQL);
339             preparedStatement.executeUpdate();
340             preparedStatement = conn.prepareStatement(DROP_TABLE_2);
341             preparedStatement.executeUpdate();
342             preparedStatement= conn.prepareStatement(CREATE_TABLE_2_SQL);
343             preparedStatement.executeUpdate();
344             conn.setAutoCommit(false);
345             conn.commit();
346             JDBCUtil.release(conn,preparedStatement);
347 
348         } catch (SQLException e) {
349             e.printStackTrace();
350             System.out.println("出现问题!建表失败!");
351         }
352     }
353     //获取文件的建表sql语句
354     public String getTableSQL(String SQL,String[] tableField, String[]fieldDescribe,String[] fieldUnit, String[] fieldType ){
355         for (int i =0 ;i<tableField.length;i++)
356         {
357             String item= tableField[i];
358             if(i!=tableField.length-1){
359                 SQL=SQL +  "`" + item + "`" +" text COMMENT "  +"\'" +fieldDescribe[i]+","+fieldUnit[i]+"\'" +" COLLATE utf8_general_ci,"+"\n";
360             }else{
361                 SQL=SQL +  "`" + item + "`" +" text COMMENT "+"\'" +fieldDescribe[i]+","+fieldUnit[i]+"\'" + " COLLATE utf8_general_ci "+"\n";
362             }
363         }
364         return SQL+") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
365     }
366 }

 

posted @ 2022-03-31 16:42  靠谱杨  阅读(589)  评论(0编辑  收藏  举报