为了熟悉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. 51nod 1289 大鱼吃小鱼 栈

    1289 大鱼吃小鱼 题目来源: Codility 基准时间限制:1 秒 空间限制:131072 KB 有N条鱼每条鱼的位置及大小均不同,他们沿着X轴游动,有的向左,有的向右.游动的速度是一样的,两条 ...

  2. SpringBoot发布到独立的tomcat中运行

    在此文基础上 Eclipse下利用Maven创建SpringBoot的Restful风格程序 spring-boot默认提供内嵌的tomcat,所以打包直接生成jar包,用java -jar命令就可以 ...

  3. Ajax接触及对跨域的简单理解

    [Ajax]Ajax技术能够向服务器请求额外的数据而无须卸载页面能带来更好的用户体验.Ajax技术的核心是XMLHttpRequest对象(简称XHR),XHR向服务器发送请求和解析拂去其响应提供了流 ...

  4. 51nod 1163 贪心

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1163 1163 最高的奖励 基准时间限制:1 秒 空间限制:131072 ...

  5. ng-file-upload - samples

    <script src="angular.min.js"></script> <!-- shim is needed to support non-H ...

  6. ElasticSearch聚合分析API——非常详细,如果要全面了解的话,最好看这个

    转自:http://www.tianyiqingci.com/2016/04/11/esaggsapi/ 前言 说完了ES的索引与检索,接着再介绍一个ES高级功能API – 聚合(Aggregatio ...

  7. [转载]java读写word文档,完美解决方案

    做项目的过程中,经常需要把数据里里的数据读出来,经过加工,以word格式输出. 在网上找了很多解决方案都不太理想,偶尔发现了PageOffice,一个国产的Office插件,开发调用非常简单!比网上介 ...

  8. 《Effective C++》——条款08:别让异常逃离析构函数

    考虑如下代码: class Widget{ public: ... ~Widget(){...}//假设这个可能吐出一个异常 }; void doSomething() { std::vector&l ...

  9. 简单常用sql查询

    [self.db executeUpdate:sql, record.recordID]; CREATE TABLE scene_record(id TEXT PRIMARY KEY, record_ ...

  10. Java VM(虚拟机) 参数

    -XX:PermSize/-XX:MaxPermSize,永久代内存: 1. 虚拟机参数:-ea,支持 assert 断言关键字 eclipse 默认是不开启此参数的,也就是虽然编译器支持 asser ...