当前位置: 首页 > 编程日记 > 正文

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

转载于:https://www.cnblogs.com/lidelin/p/6669652.html

相关文章:

9.12学习内容

操作系统基础 操作系统是协调、控制、管理计算机硬件资源与软件资源的控制程序 为什么要用操作系统&#xff1f; 1.操作系统可以把复杂的操作简化给用户使用或者应用程序 2.可以让应用程序对计算机硬件竞争变的有序 一套完整的计算机分为&#xff1a;操作系统、应用程序、计算机…

xcode 8 重新支持插件

苹果出了Xcode8之后&#xff0c;就加了签名让之前的自定义插件无法继续的安装使用。想要重新使用插件的话只要用自己的签名覆盖苹果的签名即可。 1.创建自签名证书 钥匙串-》钥匙串访问-》证书助理-》创建证书... 名称&#xff1a;XcodeSigner(可以随便命名&#xff0c;后面要使…

pda找不到服务器,PDA连不上服务器常见问题分析.doc

PDA连不上服务器常见问题分析.docPDA连不上服务器常见问题分析请查看PDA的网络通不通&#xff0c;可以先检查WIFI/3G是否连接上网络&#xff0c;如果连接不上&#xff0c;点击PingToots工具&#xff0c;用"ping 服务器地址" 比如 ping 192.168.1.1 看和服务器网络通不…

android 运动管理,使用 MotionLayout 管理运动和微件动画

创建 MotionScene&#xff1a;在之前的 MotionLayout 示例中&#xff0c;app:layoutDescription 属性引用一个 MotionScene。MotionScene 是一个 XML 资源文件&#xff0c;其中包含相应布局的所有运动描述。为了将布局信息与运动描述分开&#xff0c;每个 MotionLayout 都引用一…

ios Carthage

使用CocoaPods来管理第三方框架很多人都知道&#xff0c;相对来说Carthage比较陌生&#xff0c;Carthage也是来管理第三方框架的&#xff0c;既然已经有了Cocoapods为什么还要有Carthage呢&#xff1f;使用Carthage有什么好处呢&#xff1a; 首先&#xff0c;CocoaPods默认会自…

计算机c1 c语言答题,全国计算机级考试二级C语言上机答题技巧.doc

全国计算机等级考试二级C语言上机答题技巧1&#xff0e;上机改错的试题中通常包含两个(或三个)错误需要修改。  2&#xff0e;试题中用"******found******/"来提示在下一行(或下面第二行)有错。  3&#xff0e;错误的性质基本分语法错和逻辑错两种&#xff0c;也…

springboot +element-axios跨域请求

1、初始化element项目   1.1&#xff1a;vue init webpage 项目名称 1.2&#xff1a;npm i element-ui -S 1.3&#xff1a;在main.js添加    import ElementUI from element-uiimport element-ui/lib/theme-chalk/index.cssVue.use(ElementUI) 2、添加axios跨域请求 在main…

Nginx 主要应用场景

一、反向代理 反向代理&#xff08;Reverse Proxy&#xff09;方式是指以代理服务器来接受internet上的连接请求&#xff0c;然后将请求转发给内部网络上的服务器&#xff0c;并将从服务器上得到的结果返回给internet上请求连接的客户端。 server { listen 80; …

ios .a和.framework

创建Aggregate来合并模拟器和真机通用的framework 然后在Build Phases下New Run Script Phase创建合并脚本&#xff1a; # Constants SF_TARGET_NAME${PROJECT_NAME} #自定义的用来存放最后合并的framework UNIVERSAL_OUTPUTFOLDER${BUILD_DIR}/${CONFIGURATION}-universal #IP…

android上下文关系,Android Context上下文的理解 Hua

8种机械键盘轴体对比本人程序员&#xff0c;要买一个写代码的键盘&#xff0c;请问红轴和茶轴怎么选&#xff1f;Context概念在安卓对象中&#xff0c;Context是经常使用的元素…但应该也是错误使用率最高的。你在加载资源、启动一个新的Activity、获取系统服务、获取内部文件(…

打开云服务器连不上网,云服务器怎么连接网络连接不上

traceroute(路由跟踪)通常&#xff0c;ping程序用于确定基本连接是否通&#xff0c;traceroute实用程序可用于确定目标打开终端&#xff0c;输入traceroute&#xff0c;点击回车即可可以检测主机和目标主机之间进行交互所经过的网关数量&#xff0c;由接受的数据包来得出结果。…

Pandas缺失数据

数据丢失(缺失)在现实生活中总是一个问题。 机器学习和数据挖掘等领域由于数据缺失导致的数据质量差&#xff0c;在模型预测的准确性上面临着严重的问题。 在这些领域&#xff0c;缺失值处理是使模型更加准确和有效的重点。 何时以及为什么数据丢失&#xff1f; 想象一下有一个…

android servlet 登陆,Android Studio+Servlet+MySql实现登录注册

一、Android 项目当中设置明文传输1、设置明文传输的xml2、引入上述创建的xmlandroid:networkSecurityConfig"xml/network_security_config"二、在MyEclipse当中创建Web项目1、创建项目引入MySQL的驱动包2、创建实体类Userpackage entity;public class User {private…

tomcat在服务器上改了8080的端口之后所带来的问题

因为与IIS的端口冲突&#xff0c;有人会在服务器上改tomcat的端口。但是tomcat在服务器上将端口8080改了之后&#xff0c;可能会导致所不熟的项目在访问时只能访问前面的域名&#xff0c;用户是使用时显示的域名看不到后面的后缀&#xff0c;比如aaa.com/aa&#xff0c;用户不论…

修改git的远程仓库命令

1. 修改命令 git remte origin set-url URL 2.先删后加 git remote rm origin git remote add origin gitgithub.com:Liutos/foobar.git 3. 直接修改config文件

c# 网站在服务器上第一次请求都需要耗时很久,最.net面试题目.doc

经典.net面试这些是C#ASP.NET数据库面试题&#xff0c;全部从网上收集而来&#xff0c;经整理而发表&#xff0c;希望给大家带来帮助&#xff0c;有错误的地方还请各位高手指出&#xff0c;在下倾听指教。1. 简述private、protected、public、internal 修饰符的访问权限。答. p…

动态语言的灵活性是把双刃剑 -- 以Python语言为例

本文有些零碎&#xff0c;总题来说&#xff0c;包括两个问题&#xff1a; &#xff08;1&#xff09;可变对象&#xff08;最常见的是list dict&#xff09;被意外修改的问题&#xff0c; &#xff08;2&#xff09;对参数&#xff08;parameter&#xff09;的检查问题。 这两个…

android 绘画,Android绘图基础

绘图三要素一支画笔 Paint。一张画布 Canvas。一个 Bitmap 或者一个 View 来承载这个图形。Paint常用属性setAntiAlias() 设置画笔锯齿效果。setColor() 设置画笔颜色。setTextSize() 设置字体尺寸。setStrokeWidth() 设置空心边框的宽度。setStyle() 设置画笔的风格。Canvas常…

源码0306-手势解锁

现搭建页面 // VCView.h // 06-手势解锁#import <UIKit/UIKit.h>interface VCView : UIViewend// VCView.m // 06-手势解锁#import "VCView.h"implementation VCView - (void)drawRect:(CGRect)rect {// 绘图图像UIImage *image [UIImage imageNamed:&quo…

about ajax,About 4nf.org - Arvind Gupta | Ajaxify | The Ajax Plugin

Hi Tony,That page shows various example calls and example websites, that use this plugin.Also, 4nf.org serves as an example, that is a fairly complex WordPress site.By default “previewoff” is true, so that swaps of the content div(s) are performed on cli…

numpy.random.seed()

numpy.random.seed()&#xff1a;用于指定随机数生成时使用算法的开始值&#xff0c;如果没有指定每次生成的值都不一样 如果不指定seed的值&#xff0c;那么每次随机生成的数字都不一样&#xff1a; In [17]: import numpy as npIn [18]: i 0In [19]: while i < 5:...: …

ios .framework动态库重签名

真机上运行.framework时&#xff0c;如果报 dylddyld_fatal_error:dyld: Library not loaded: rpath/XX.framework/XXReferenced from: /var/containers/Bundle/Application/DF33E1CB-0A69-4303-A22A-686E643DE922/iDoctors.app/iDoctors Reason: no suitable image found. Did…

canvars 画花

index.html<!DOCTYPE html><html><head> <title>旋转的花</title> <meta charset "utf-8"> <!--width - 可视区域的宽度&#xff0c;值可为数字或关键词device-width --> <!--height - viewport的高度--&…

android google 下拉刷新 csdn,android SwipeRefreshLayout google官方下拉刷新控件

下拉刷新功能之前一直使用的是XlistView很方便我前面的博客有介绍SwipeRefreshLayout是google官方推出的下拉刷新控件使用方法也比较简单今天就来使用下SwipeRefreshLayout 以后再需要时可以参考.首先在布局里面加入SwipeRefreshLayout 布局:Activity文件中的代码mSwipeRefresh…

服务器操作系统安全更新,服务器操作系统安全更新

服务器操作系统安全更新 内容精选换一换使用弹性云服务器或者外部镜像文件创建私有镜像时&#xff0c;必须确保操作系统中已安装UVP VMTools&#xff0c;使新发放的云服务器支持KVM虚拟化&#xff0c;同时也可以提升云服务器的网络性能。如果不安装UVP VMTools&#xff0c;云服…

流程控制if、while、for

if判断 if判断想执行第一个条件&#xff0c;if后的判断必须是True 1 什么是if判断   判断一个条件如果成立则做...不成立则做....2 为何要有if判断   让计算机能够像人一样具有判断的能力3 如何用if判断 语法1: if 条件1:code1code2code3...... 语法2:if-else if 条件:code…

抄写例题作业1

截图 1.例9.1 &#xff08;1&#xff09;代码实现 1 #include<stdio.h>2 int main()3 {4 struct stu5 {6 long int num;7 char name[20];8 char sex[3];9 char addr[20]; 10 }a{1010,"董诗原","男",&qu…

android button imagebutton 区别,Android 开发入门篇

Button 与 ImageButton本节学习Android基本控件按钮控件&#xff0c;Button和ImageButton用法基本类似&#xff0c;所以本节重点讲解Button控件。在布局中添加Button控件&#xff1a;android:id"id/btn"android:text"普通按钮"android:layout_width"w…

iOS autolayout 约束冲突添加symbol breakpoint

UIViewAlertForUnsatisfiableConstraints

Win7安装ant

下载ant&#xff0c;当前版本是1.9.4。下载地址点击打开链接。 解压到你喜欢的路径下面&#xff0c;我喜欢D:\Program Files\apache-ant-1.9.4 配置环境变量ANT_HOME。右击计算机→选择属性→高级系统设置→“高级”标签→环境变量。 新建系统变量。变量名必须是“ANT_HOME…