java 将文件数据导入至数据库

1.建立maven工程(方便管理jar包)


在pom.xml导入 jxl,mysql-connector 依赖

可以在maven仓库搜索

2.建立数据库连接类,数据库对应实体类

2.编写数据库表对应的实体类 ,get、set方法等

3.下面是编写读取excel文件的类 ,和运行主类

复制代码

package service;


import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import excel.DB;
import excel.Student;


public class StudentService {
    /**
     * 查询Student表中所有的数据
     * @return 
     */
    public static List<Student> getAllByDb(){
        List<Student> list=new ArrayList<Student>();
        try {
            DB db=new DB();
            String sql="select * from student";
            ResultSet rs= db.Search(sql, null);
            while (rs.next()) {
                int id=rs.getInt("id");
                String s_name=rs.getString("s_name");
                String age=rs.getString("age");
                String address=rs.getString("address");
                
                list.add(new Student(id, s_name, age,address));
            }
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
    
    /**
     * 查询指定目录中电子表格中所有的数据
     * @param file 文件完整路径
     * @return
     */
    public static List<Student> getAllByExcel(String file){
        List<Student> list=new ArrayList<Student>();
        try {
            Workbook rwb=Workbook.getWorkbook(new File("F:\\student.xls"));
            Sheet rs=rwb.getSheet(0);//表
            int clos=rs.getColumns();//得到所有的列
            int rows=rs.getRows();//得到所有的行
            
            System.out.println("表的列数:"+clos+" 表的行数:"+rows);
            for (int i = 1; i < rows; i++) {
                for (int j = 0; j < clos; j++) {
                    //第一个是列数,第二个是行数
                    String id=rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++
                   
                    String s_name=rs.getCell(j++, i).getContents();
                    String age=rs.getCell(j++, i).getContents();
                    String address=rs.getCell(j++, i).getContents();
                    
                    System.out.println("id:"+id+" name:"+s_name+" sex:"+age+" address:"+address);
                    list.add(new Student(Integer.parseInt(id), s_name,age,address));
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return list;
        
    }
    
    /**
     * 通过Id判断是否存在
     * @param id
     * @return
     */
    public static boolean isExist(int id){
        try {
            DB db=new DB();
            ResultSet rs=db.Search("select * from student where id=?", new String[]{id+""});
            if (rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    
    public static void main(String[] args) {
        
        
        System.out.println(isExist(1));
        
    }
    
}

复制代码

运行主类:

复制代码

package service;


import java.util.List;

import excel.DB;
import excel.Student;


public class TestExcelToDb {
    public static void main(String[] args) {
        //得到表格中所有的数据
        List<Student> listExcel=StudentService.getAllByExcel("F:\\student.xls");
                
      
        
        DB db=new DB();
        
        for (Student student : listExcel) {
            int id=student.getId();
            System.out.println(id);
            if (!StudentService.isExist(id)) {
                //不存在就添加
                String sql="insert into student (id,s_name,age,address) values(?,?,?,?)";
                String[] str=new String[]{id+"",student.getS_name(),student.getAge(),student.getAddress()+""};
                db.AddU(sql, str);
            }else {
                //存在就更新
                String sql="update student set s_name=?,age=?,address=? where id=?";
                String[] str=new String[]{student.getS_name(),student.getAge(),student.getAddress()+"",id+""};
                db.AddU(sql, str);
            }
        }
    }
}

复制代码

数据库截图:[Excel数据表头要与数据库字段对应]

总结:以上是使用了 jxl实现的读取excel文件内容,并且将数据传到mysql,缺陷是:jxl仅支持EXCEL2003。

   要改进兼容2003和2007需要使用pol,要导入pol相关jar包

    pol 里面有有两个类是处理Excel2003 和Excel2007的

    HSSF-----2003,XSSF-----2007

下面是通过读取文件名判断该文件类型是03还是07的类方法。因为03和07很显然在文件后缀名就存在区别

复制代码

/**
     * 对外提供读取excel 的方法
     * */
    public static List<String> readExcel(File file) throws IOException {
        String fileName = file.getName();
        List<String> list = new ArrayList<String>();
        //根据其名称获取后缀
        String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName
                .substring(fileName.lastIndexOf(".") + 1);
        String[][] result = null;
        if ("xls".equals(extension)) {
            result = read2003Excel(file);
        } else if ("xlsx".equals(extension)) {
            result = read2007Excel(file);
        } else {
            throw new IOException("不支持的文件类型");
        }
        int rowLength = result.length;
        
        for (int i = 0; i < rowLength; i++) {
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < result[i].length; j++) {
                if(!"".equals(result[i][j]) && result[i][j].trim().length()>0){
                    sb.append(result[i][j]).append("##");
                }else{
                    sb.append("@@").append("##");
                }
            }
            if(sb.toString().endsWith("##")){
                sb.delete(sb.toString().length()-2, sb.toString().length());
            }
            System.out.println(sb.toString());
            list.add(sb.toString());
        }
        return list;
    }

复制代码

然后根据上面在编写一个读取Excel2003和一个Excel2007的类就行了。

以上是个人在测试编写后做的一点记录,有不对的地方望指正和见谅。

转载 https://www.cnblogs.com/cx-code/p/9111336.html

猜你喜欢

转载自blog.csdn.net/weixin_40790313/article/details/85060145