为了熟悉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);
        }
    }
}
}
笔者水平有限,难免有错误,仅供参考!

Excel向数据库插入数据和数据库向Excel导出数据的更多相关文章

  1. 【HIVE】(1)建表、导入数据、外部表、导出数据

    导入数据 1). 本地 load data local inpath "/root/example/hive/data/dept.txt" into table dept; 2). ...

  2. 把Oracle的数据导入到SQL2012中 导出数据--SSIS

    在ORACLE表和SQL Server表之间'转换'那步很重要,可以改变默认的字段数据类型,如image->text,decimal->int number  ->int (注意设置 ...

  3. MySQL数据库使用mysqldump导出数据详解

    mysqldump是mysql用于转存储数据库的实用程序.它主要产生一个SQL脚本,其中包含从头重新创建数据库所必需的命令CREATE TABLE INSERT等.接下来通过本文给大家介绍MySQL数 ...

  4. 本地Sql Server数据库传到服务器数据库

    将网站项目上传到服务器时,会遇到本地数据库该如何上传的问题.下面在西部数码购买的虚拟主机的基础上,解决数据库上传问题.   1.在西部数码购买虚拟主机后,会赠送了一个数据库,该数据库就可以作为网站项目 ...

  5. 导出数据到Excel表格

    开发工具与关键技术:Visual Studio 和 ASP.NET.MVC,作者:陈鸿鹏撰写时间:2019年5月25日123下面是我们来学习的导出数据到Excel表格的总结首先在视图层写导出数据的点击 ...

  6. 利用mysqldump 将一个表按条件导出数据

    mysqldump -uroot -pdsideal -t dsideal_db t_resource_info --where="res_type=1 and group_id=1 and ...

  7. mysql导入导出数据

    mysqldump是MySQL自带的导出数据工具,通常我们用它来导出MySQL中,但是有时候我们需要导出MySQL数据库中某个表的部分数据作为测试. mysqldump命令中带有一个 --where/ ...

  8. sqlite迁移mysql(导入导出数据)

    第一步,将数据导出 进入sqlite3->.open [打开文件路径]->.cd [要保存的路径]->.output [导出文件名字.sql]->.dump 等待导出成功后,就 ...

  9. Excel向数据库插入数据(执行一次只需连接一次)-batch简单使用

    由于前端时间向数据库插入excel中的数据时,每插入一条数据,就得连接一次数据库:后来发现这种做法不好,如果excel中有很多条数据,就得连接很多次数据库,这样就很浪费资源而且不安全,有时数据库也会报 ...

随机推荐

  1. java项目 里的DAO,model,service, IMPL含义

    在一般工程中 基本上都会出现上述的字眼首先 DAO 提供了应用程序与数据库之间的操作规范 和操作 用于通常数据库的增删查改 一般如果使用框架 都是由框架自动生成,提高访问效率和便于快速开发.hiber ...

  2. js建造者(生成器)模式

    建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示. 在软件系统中,有时需要创建一个复杂对象,并且这个复杂对象由其各部分子对象通过一定的步骤组合而成. 建造者模式类图: ...

  3. WPF利用通过父控件属性来获得绑定数据源RelativeSource

    WPF利用通过父控件属性来获得绑定数据源RelativeSource   有时候我们不确定作为数据源的对象叫什么名字,但知道作为绑定源与UI布局有相对的关系,如下是一段XAML代码,说明多层布局控件中 ...

  4. 清北学堂(2019 5 1) part 4

    今天讲数论 1.进制问题(将n转换成k进制数): 1.方法:短除法 将n/k,保存,将商当做新的n,将余数保存,直到商为0,将余数(包括0),倒序输出,即得n的k进制数 2.关于高精四则运算(我本以为 ...

  5. ASP.NET Core 开源项目整理

    前言: 对 .NET Core 的热情一直没有下降过,新起的项目几乎都是采用 Core 来做开发. 跨平台是一个方面,另外就是 Core 很轻,性能远超很多开发语言(不坑). 一.ASP.NET Co ...

  6. jar包作用

    hibernate中jar包的作用 (1)hibernate3.jar:Hibernate的核心库,没有什么可说的,必须使用的jar包 (2)cglib-asm.jar:CGLIB库,Hibernat ...

  7. 用new Image().src作LOG统计的一个注意事项 .

    用new Image().src作LOG统计的一个注意事项 2009-08-06 17:40 在大型网站做很多用户行为分析.产品的策划方案基本上都是通过分析用户的访问等信息而做出的,LOG信息的统计准 ...

  8. JVM_总结_00_资源帖

    一.官方资料 Java Platform Standard Edition 8 Documentation The Java™ Tutorials Java 8 API 二.精选资料 发布<Ja ...

  9. jira 从数据库 切换到mysql

    通过JIRA管理员登录,进入“管理员页面”,“系统”--“导入&导出”,以XML格式备份数据. 在MySQL中创建Schema,命名为jira 关闭JIRA服务 备份一下JIRA的安装目录和数 ...

  10. nyoj-1132-promise me a medal(求线段交点)

    题目链接 /* Name:nyoj-1132-promise me a medal Copyright: Author: Date: 2018/4/26 20:26:22 Description: 向 ...