excel向mysql写入数据_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

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

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

List list=new ArrayList();

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 getAllByExcel(String file){

List stus=new ArrayList();

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

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 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

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 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);

}

}

}

}

笔者水平有限,难免有错误,仅供参考!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值