java Excel导入导出 Mysql

1 项目结构目录

2 实体类 entity

package entity;

import jxl.write.DateTime;

public class Tb_Student {

    private int id;

    private String name;

    private String sex;

    private int age;

    private String register_date;

    public int getId() {

       return id;

    }

    public void setId(int id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public String getSex() {

       return sex;

    }

    public void setSex(String sex) {

       this.sex = sex;

    }

    public int getAge() {

       return age;

    }

    public void setAge(int age) {

       this.age = age;

    }

    public String getRegister_date() {

       return register_date;

    }

    public void setRegister_date(String register_date) {

       this.register_date = register_date;

    }

    public Tb_Student() {

       super();

    }

    public Tb_Student(int id, String name, String sex, int age,

           String register_date) {

       super();

       this.id = id;

       this.name = name;

        this.sex = sex;

       this.age = age;

       this.register_date = register_date;

    }

    @Override

    public String toString() {

       return "Tb_Student [id=" + id + ", name=" + name + ", sex=" + sex

              + ", age=" + age + ", register_date=" + register_date + "]";

    }

}

3 service

package service;

import java.io.File;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import utils.DBUtil;

import entity.Tb_Student;

import jxl.Sheet;

import jxl.Workbook;

/** 

 * <p>Title: file_name</p> 

 * <p>Description: Service类 </p> 

 * <p>Copyright: Copyright (c) 2018</p> 

 * <p>Company: www.ZTESoft.com</p> 

 * @author @yrf 

 * @date 2018年8月10日 

 * @version 1.0 

 */

public class ExcelService {

     //查询tb_student表中所有的数据

    public static List<Tb_Student> getAllByDb(){

        List<Tb_Student> list=new ArrayList<Tb_Student>();

        try {

            DBUtil db=new DBUtil();

            String sql="select * from tb_student";

            ResultSet rs= db.Search(sql, null);

            while (rs.next()) {

                int id=rs.getInt("id");

                String name=rs.getString("name");

                String sex=rs.getString("sex");

                int age=rs.getInt("age");

                String register_date=rs.getString("register_date");

                list.add(new Tb_Student(id, name, sex, age,register_date));

            }

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return list;

    }

    //查询指定目录中电子表格中所有的数据

    public static List<Tb_Student> getAllByExcel(String file){

        List<Tb_Student> list=new ArrayList<Tb_Student>();

        try {

            Workbook rwb=Workbook.getWorkbook(new File(file));

            Sheet rs=rwb.getSheet("Test Shee 1");

            int clos=rs.getColumns();//得到所有的列

            int rows=rs.getRows();//得到所有的行

            System.out.println(clos+" rows:"+rows);

            for (int i = 1; i < rows; i++) {

                for (int j = 0; j < clos; j++) {

                    //第一个是列数j,第二个是行数i

//                    String id=rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++

                    String id = "0";

                    String name=rs.getCell(j++, i).getContents();

                    String sex=rs.getCell(j++, i).getContents();

                    String age=rs.getCell(j++, i).getContents();

                    Date date =new Date();

                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss");

                    String register_date=sdf.format(date);

                    System.out.println("id:"+id+" name:"+name+" sex:"+sex+" age:"+age+" register_date:"+register_date);

                    list.add(new Tb_Student(Integer.parseInt(id), name, sex, Integer.parseInt(age),register_date));

                }

            }

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return list;

    }

   

    /**

     * 通过Id判断是否存在

     * @param id

     * @return

     */

    public static boolean isExist(int id){

        try {

            DBUtil db=new DBUtil();

            ResultSet rs=db.Search("select * from tb_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) {

        /*List<StuEntity> all=getAllByDb();

        for (StuEntity stuEntity : all) {

            System.out.println(stuEntity.toString());

        }*/

        System.out.println(isExist(1));

    }

}

4 工具类 DBUtil

package utils;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

/** 

 * <p>Title: file_name</p> 

 * <p>Description: excel的导入与导出</p> 

 * <p>Copyright: Copyright (c) 2018</p> 

 * <p>Company: www.ZTESoft.com</p> 

 * @author @yrf 

 * @date 2018年8月10日 

 * @version 1.0 

 */

public class DBUtil {

    String driver = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://127.0.0.1:3306/excel_mysql";

    Connection con = null;

    ResultSet res = null;

    public void DataBase() {

            try {

                Class.forName(driver);

                con = DriverManager.getConnection(url, "root", "root");

            } catch (ClassNotFoundException e) {

                  System.err.println("装载 JDBC/ODBC 驱动程序失败。" ); 

                e.printStackTrace();

            } catch (SQLException e) {

                System.err.println("无法连接数据库" );

                e.printStackTrace();

            }

    }

    // 查询

    public ResultSet  Search(String sql, String str[]) {

        DataBase();

        try {

            PreparedStatement pst =con.prepareStatement(sql);

            if (str != null) {

                for (int i = 0; i < str.length; i++) {

                    pst.setString(i + 1, str[i]);

                }

            }

            res = pst.executeQuery();

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return res;

    }

    // 增删修改

    public int AddU(String sql, String str[]) {

        int a = 0;

        DataBase();

        try {

            PreparedStatement pst = con.prepareStatement(sql);

            if (str != null) {

                for (int i = 0; i < str.length; i++) {

                    pst.setString(i + 1, str[i]);

                }

            }

            a = pst.executeUpdate();

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return a;

    }

}

5 从Mysql数据库导出excel表 ExcelExport类

package test;

import java.io.File;

import java.util.List;

import entity.Tb_Student;

import service.ExcelService;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

/** 

 * <p>Title: file_name</p> 

 * <p>Description: 导出Excel表 </p> 

 * <p>Copyright: Copyright (c) 2018</p> 

 * <p>Company: www.ZTESoft.com</p> 

 * @author @yrf 

 * @date 2018年8月10日 

 * @version 1.0 

 */

public class ExcelExport {

    public static void main(String[] args) {

        try {

            WritableWorkbook wwb = null;

               // 创建可写入的Excel工作簿

               String fileName = "D://test//exceltest//Student.xls";

               File file=new File(fileName);

               if (!file.exists()) {

                   file.createNewFile();

               }

               //以fileName为文件名来创建一个Workbook

               wwb = Workbook.createWorkbook(file);

               // 创建工作表

               WritableSheet ws = wwb.createSheet("Test Shee 1", 0);

               //查询数据库中所有的数据

               List<Tb_Student> list= ExcelService.getAllByDb();

               //要插入到的Excel表格的行号,默认从0开始

               Label labelId= new Label(0, 0, "编号(id)");//表示第

               Label labelName= new Label(1, 0, "姓名(name)");

               Label labelSex= new Label(2, 0, "性别(sex)");

               Label labelAge= new Label(3, 0, "年龄(age)");

               Label labelRegister_date= new Label(4, 0, "注册时间(register_date)");

               ws.addCell(labelId);

               ws.addCell(labelName);

               ws.addCell(labelSex);

               ws.addCell(labelAge);

               ws.addCell(labelRegister_date);

               for (int i = 0; i < list.size(); i++) {

                   Label labelId_i= new Label(0, i+1, list.get(i).getId()+"");

                   Label labelName_i= new Label(1, i+1, list.get(i).getName());

                   Label labelSex_i= new Label(2, i+1, list.get(i).getSex());

                   Label labelAge_i= new Label(3, i+1, list.get(i).getAge()+"");

                   Label labelRegister_date_i= new Label(4, i+1, list.get(i).getRegister_date()+"");

                   ws.addCell(labelId_i);

                   ws.addCell(labelName_i);

                   ws.addCell(labelSex_i);

                   ws.addCell(labelAge_i);

                   ws.addCell(labelRegister_date_i);

               }

              //写进文档

               wwb.write();

              // 关闭Excel工作簿对象

               wwb.close();

               System.out.println("导出Excel成功");

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

}

6 ExcelImport类  excel表数据导入Mysql数据库

package test;

import java.util.List;

import service.ExcelService;

import utils.DBUtil;

import entity.Tb_Student;

/** 

 * <p>Title: file_name</p> 

 * <p>Description: 导入Excel表</p> 

 * <p>Copyright: Copyright (c) 2018</p> 

 * <p>Company: www.ZTESoft.com</p> 

 * @author @yrf 

 * @date 2018年8月10日 

 * @version 1.0 

 */

public class ExcelImport {

    public static void main(String[] args) {

        //得到表格中所有的数据

        List<Tb_Student> listExcel=ExcelService.getAllByExcel("D://test//exceltest//Student2.xls");

        /*//得到数据库表中所有的数据

        List<StuEntity> listDb=StuService.getAllByDb();*/

        DBUtil db=new DBUtil();

        for (Tb_Student list : listExcel) {

            int id=list.getId();

            System.out.println("id"+id);

            if (!ExcelService.isExist(id)) {

                //不存在就添加

                String sql="insert into tb_student (name,sex,age,register_date) values(?,?,?,?)";

                String[] str=new String[]{list.getName(),list.getSex(),list.getAge()+"",list.getRegister_date()};

                db.AddU(sql, str);

            }else {

                //存在就更新

                String sql="update tb_student set name=?,sex=?,num=? where id=?";

                String[] str=new String[]{list.getName(),list.getSex(),list.getAge()+"",list.getRegister_date(),id+""};

                db.AddU(sql, str);

            }

            System.out.println("数据导入成功");

        }

    }

}

7 功能总结

Id 是自动生成的 Register_date 是根据系统时间自动生成的 然后把id register_date插入到数据库中。

源码路径下载github地址: https://github.com/yuanruofei/excel_mysql

猜你喜欢

转载自blog.csdn.net/yloveyzcl/article/details/81747453