天天看點

Excel向資料庫插入資料和資料庫向Excel導出資料

為了熟悉java裡工作簿的相關知識點,是以找了“Excel向資料庫插入資料和資料庫向Excel導出資料”的功能來實作。

注意事項:1,mysql資料庫;

              2,需要導入的jar包有 jxl.jar,mysql-connector-java-5.1.22-bin.jar,ojdbc6.jar

代碼如下:

一, 建立資料庫名稱 javaforexcel,建立表stu

DROP TABLE IF EXISTS `stu`;

CREATE TABLE `stu` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(20) DEFAULT NULL,

  `sex` char(2) DEFAULT NULL,

  `num` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

二 ,建實體類

package com.excel.model;

public class Stu {

 private int id;//ID

 private String name;//姓名

 private String sex;//性别

 private int num;//工資

public Stu(int id, String name, String sex, int num) {

    this.id = id;

    this.name = name;

    this.sex = sex;

    this.num = num;

}

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 getNum() {

    return num;

}

public void setNum(int num) {

    this.num = num;

}

}

三,建立資料庫連接配接,這裡隻是簡單的測試,本來應該寫在common包,我就寫在dao包裡邊了

package com.excel.dao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

public class DBhelper {

 Connection con=null;

 ResultSet res=null;

 PreparedStatement pre=null;

 //連接配接資料庫

 public void DBbase(){

     try {

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

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

        String userName="root";

        String passWord="";

        Class.forName(driver);

        con=DriverManager.getConnection(url,userName,passWord);

    } catch (Exception e) {

        e.printStackTrace();

    }

 }

 //查詢

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

     DBbase();

     try {

        pre=con.prepareStatement(sql);

        if(args!=null){

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

                pre.setString(i+1, args[i]);

            }

        }

        res=pre.executeQuery();

    } catch (Exception e) {

        e.printStackTrace();

    }

    return res;

 }

 //增删改

 public int Adu(String sql,String args[]){

     int falg=0;

     DBbase();

     try {

        pre=con.prepareStatement(sql);

        if(args!=null){

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

                pre.setString(i+1, args[i]);

            }

        }

        falg=pre.executeUpdate();

    } catch (Exception e) {

        e.printStackTrace();

    }

    return falg;

 }

}

四,事務層方法如下:

package com.excel.service;

import java.io.File;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;

import jxl.Sheet;

import jxl.Workbook;

import com.excel.dao.DBhelper;

import com.excel.model.Stu;

public class StuService {

/*

 * 查詢stu表中左右資料

 */

    public static List<Stu> getAllByDB(){

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

        try {

            DBhelper dBhelper=new DBhelper();

            String sql="select * from stu";

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

            while(rs.next()){

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

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

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

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

                list.add(new Stu(id, name, sex, num));

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return list;

    }

    /**

     * 查詢指定目錄中電子表格中所有的資料

     * @param file 檔案完整路徑

     * @return

     */

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

        List<Stu> stus=new ArrayList<Stu>();

        try {

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

            Sheet sheet=wb.getSheet("Test");

            int cols=sheet.getColumns();//得到總的列數

            int rows=sheet.getRows();//得到總的行數

            System.out.println("列數:"+cols+" 行數:"+rows);

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

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

                    //第一個是列數,第二個是行數

                    String id=sheet.getCell(j++, i).getContents();//預設最左邊編号也算一列 是以這裡得j++

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

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

                    String num=sheet.getCell(j++,i).getContents();

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

                    stus.add(new Stu(Integer.parseInt(id), name, sex, Integer.parseInt(num)));

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return stus;

    }

    /**

     * 通過Id判斷是否存在

     * @param id

     * @return

     */

    public static boolean isExist(int id){

        boolean flag=false;

        try {

            DBhelper dB=new DBhelper();

            ResultSet rs=dB.Search("select * from stu where id=?", new String[]{id+""});

            if (rs.next()) {

                flag=true;

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return flag;

    }

}

五,資料庫向Excel裡導入資料

package com.excel.control;

import java.io.File;

import java.util.List;

import com.excel.model.Stu;

import com.excel.service.StuService;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

public class DBInExcel {

public static void main(String[] args) {

    try {

        WritableWorkbook rb = null;//建立一個可寫的Workbook

        WritableSheet    ws = null;// 建立工作表

        String FileName = "C://Users//lidelin//Desktop//test.xls";//建立可寫入的Excel工作簿位址及名稱

        File file=new File(FileName);

        if(!file.exists()){

            file.createNewFile();

        }

        rb = Workbook.createWorkbook(file);//以fileName為檔案名來建立一個Workbook

        ws = rb.createSheet("Test", 0);

        List<Stu> stus=StuService.getAllByDB();//查詢資料庫中所有的資料

        //行和列都是0開始

        Label laId=new Label(0, 0,"編号ID");//1列1行

        Label laName=new Label(1, 0,"姓名Name");//2列1行

        Label laSex=new Label(2, 0,"性别Sex");//3列1行

        Label laNum=new Label(3, 0,"姓名Num");//4列1行

        ws.addCell(laId);

        ws.addCell(laName);

        ws.addCell(laSex);

        ws.addCell(laNum);

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

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

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

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

            Label labelNum_i= new Label(3, i+1, stus.get(i).getNum()+"");

            ws.addCell(labelId_i);

            ws.addCell(labelName_i);

            ws.addCell(labelSex_i);

            ws.addCell(labelNum_i);

        }

        rb.write();//寫進文檔

        System.out.println("已經将資料寫入指定檔案,請檢視!");

        rb.close();//關閉Excel工作簿對象

    } catch (Exception e) {

        e.printStackTrace();

    }

}

}

六,Excel向資料庫導入資料

package com.excel.control;

import java.util.List;

import com.excel.dao.DBhelper;

import com.excel.model.Stu;

import com.excel.service.StuService;

public class ExcelInDB {

public static void main(String[] args) {

    List<Stu> stus=StuService.getAllByExcel("C://Users//lidelin//Desktop//test.xls");//查詢資料庫中所有的資料

    DBhelper dB=new DBhelper();

    for (Stu stu:stus) {

        int id=stu.getId();

        if (!StuService.isExist(id)) {//不存在就添加

            String sql="insert into stu (name,sex,num) values (?,?,?)";

            String[] str={stu.getName(),stu.getSex(),stu.getNum()+""};

            dB.Adu(sql, str);

        }else {//存在就更新

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

            String[] str={stu.getName(),stu.getSex(),stu.getNum()+"",id+""};

            dB.Adu(sql, str);

        }

    }

}

}

筆者水準有限,難免有錯誤,僅供參考!