三、导入csv格式的excel

来源:互联网 发布:linux chown -x -r 编辑:程序博客网 时间:2024/05/16 09:26
package com.cmdi.dataloader;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;import java.util.StringTokenizer;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Service;@Service@Scope("singleton")public class CsvImport extends ImportData {private List<String> rowList = new ArrayList<String>(); private List<List<String>> list = new ArrayList<List<String>>();private CsvImport(){get_import_list().add(this);}//private static CsvImport csvImport=new CsvImport();public List<List<String>> read(String filePath){//验证文件的合法性if(!validateExcel(filePath)){return null;}try {             File csv = new File(filePath); // CSV文件//            BufferedReader br = new BufferedReader(new FileReader(csv));            DataInputStream in = new DataInputStream(new FileInputStream(csv));             BufferedReader br= new BufferedReader(new InputStreamReader(in,"GBK"));//设置输出的编码            // 读取直到最后一行             String line = ""; //            当前行            int cur = 0;            while ((line = br.readLine()) != null) {                 // 把一行数据分割成多个字段                 StringTokenizer st = new StringTokenizer(line, ",");                List<String> tempList = new ArrayList<String>();                while (st.hasMoreTokens()) {                     // 每一行的多个字段用TAB隔开表示 //                    System.out.print(st.nextToken() + "/t");                    rowList.add(st.nextToken());                }                 if(cur>0){                for (int i = 1; i < rowList.size(); i++) {//i是指当前行                tempList.add(rowList.get(i));//将每行数据放进tempList                }                rowList.clear();                list.add(tempList);//将每行的数据 存进 list                }else{                rowList.clear();                }                cur++;            }             br.close();        } catch (FileNotFoundException e) {             // 捕获File对象生成时的异常             e.printStackTrace();         } catch (IOException e) {             // 捕获BufferedReader对象关闭时的异常             e.printStackTrace();         } //返回csv的所有数据return list;}public boolean validateExcel(String filePath) {// TODO Auto-generated method stubif (filePath == null|| !(isCsv(filePath))) {return false;}/** 检查文件是否存在 */File file = new File(filePath);if (file == null || !file.exists()) {return false;}return true;}public static boolean isCsv(String filePath) {return filePath.matches("^.+\\.(?i)(csv)$");}}

0 0
原创粉丝点击