package com.datahander; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import com.csvreader.CsvReader; import com.util.Manager; public class ReadCsv { private static boolean flag = false;; /** * csv文件导数 * @param file */ public static void cvsManager(File file){ if(file.exists() || file.length() > 0){ flag = isPics(file.getName()); if(!flag){ System.out.println("文件格式错误"); }else{ try { List<String[]> csvList = new ArrayList<String[]>(); //用来保存数据 String csvFilePath = file.getPath(); CsvReader reader = null; try{ reader = new CsvReader(csvFilePath, ‘,‘, Charset.forName("UTF-8")); //reader.readHeaders(); // 跳过表头 如果需要表头的话,不要写这句。 int lineSum = 0; int count = 1000; while(reader.readRecord()){ //逐行读入除表头的数据 lineSum ++; String s[]=reader.getValues(); for(int i=0;i<s.length;i++){ s[i]=s[i].replaceAll("‘",""); s[i]=s[i].replaceAll("\\\\","/"); } System.out.println(s); csvList.add(s); if(lineSum % count == 0){ importDataToMySql(csvList); //调用导数的方法 System.out.println("已插入1000条"); csvList.clear(); } } importDataToMySql(csvList); csvList.clear(); System.err.println("插入完成!"); }finally{ reader.close(); } }catch(Exception ex){ System.out.println(ex); } } }else{ System.err.println("文件不存在或文件为空!"); } } /** * 将集合导入到数据库中去 * @param csvList */ public static void importDataToMySql(List<String[]> csvList){ String va = ""; String table="cvsdatas"; String val="(company_name,cate_name,province,city,area,address,contact_people,contact_phone,telephone,website,email,latitude,longitude,product,description,logo,company_id)"; for(int row=0;row<csvList.size();row++){ va+="(‘" + csvList.get(row)[0]+"‘,‘"+csvList.get(row)[1]+"‘,‘"+csvList.get(row)[2]+"‘,‘"+csvList.get(row)[3]+"‘,‘"+csvList.get(row)[4]+"‘,‘"+csvList.get(row)[5]+"‘,‘"+csvList.get(row)[6]+"‘,‘"+csvList.get(row)[7]+"‘,‘"+csvList.get(row)[8]+"‘,‘"+csvList.get(row)[9]+"‘,‘"+csvList.get(row)[10]+"‘,‘"+csvList.get(row)[11]+"‘,‘"+csvList.get(row)[12]+"‘,‘"+csvList.get(row)[13]+"‘,‘"+csvList.get(row)[14]+"‘,‘"+csvList.get(row)[15]+"‘,‘"+csvList.get(row)[16]+ "‘),"; } va=va.substring(0, va.length()-1); Manager.insertData(table,va,val); } public static boolean isPics(String filename) { boolean flag = false; if(filename.endsWith(".csv")) flag = true; return flag; } }
时间: 2024-10-05 14:22:23