为了熟悉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. js数字过大js自动变0

    解决方案: <a onclick="checkDate(${item.billday},'${item.bankcard}',${item.limitmoney/100}) 加上引号变 ...

  2. VS10_慢_优化

    参考网址: http://blog.csdn.net/cll131421/article/details/15341367 1. 我暂时只做了这个: “ 一.VS2010选项视觉体验设置 工具-> ...

  3. redis 按空间范围查询点位

    GEORADIUS GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [ASC| ...

  4. keystone cache

    http://docs.openstack.org/juno/config-reference/content/section_keystone.conf.html http://docs.opens ...

  5. 根据图片名字在drawable中得到图片

    int imageId = context.getResources().getIdentifier("图片的名字","drawable", "包名& ...

  6. dp4--codeVs1043 方格取数

    dp4--codeVs1043 方格取数 一.心得 二.题目 1043 方格取数 2000年NOIP全国联赛提高组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Dia ...

  7. 2D游戏摄像机跟随不出界

    做2D游戏的时候碰上摄像机要跟随人物时要防止摄像机看到界面外的黑幕,直接上代码. using System.Collections; using System.Collections.Generic; ...

  8. MySQL 基础知识(基本架构、存储引擎差异)

    前言: // MySQL 并发.异步IO.进程劫持 最近在看高性能 MySQL,记录写学习笔记: 高性能 MySQL 学习笔记(一) 架构与历史 笔记核心内容:MySQL 服务器基础架构.各种存储引擎 ...

  9. mysql 视图、触发器、事物、存储过程、函数

    一 视图 视图是一个虚拟表(非真实存在),其本质是[根据SQL语句获取动态的数据集,并为其命名],用户使用时只需使用[名称]即可获取结果集,可以将该结果集当做表来使用. 使用视图我们可以把查询过程中的 ...

  10. 33 python 并发编程之IO模型

    一 IO模型介绍 为了更好地了解IO模型,我们需要事先回顾下:同步.异步.阻塞.非阻塞 同步(synchronous) IO和异步(asynchronous) IO,阻塞(blocking) IO和非 ...