java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中。
你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息
使用JXL技术可以在 :java的jxl技术导入Excel
项目结构:

Excel中的测试数据:

数据库结构:

对应的SQL:
CREATE TABLE `student_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`no` varchar(20) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
`age` varchar(10) DEFAULT NULL,
`score` float DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入数据成功:

如果重复数据,则丢掉:

=============================================
源码部分:
=============================================
/ExcelTest/src/com/b510/client/Client.java
/**
*
*/
package com.b510.client; import java.io.IOException;
import java.sql.SQLException; import com.b510.excel.SaveData2DB; /**
* @author Hongten
* @created 2014-5-18
*/
public class Client { public static void main(String[] args) throws IOException, SQLException {
SaveData2DB saveData2DB = new SaveData2DB();
saveData2DB.save();
System.out.println("end");
}
}
/ExcelTest/src/com/b510/common/Common.java
/**
*
*/
package com.b510.common; /**
* @author Hongten
* @created 2014-5-18
*/
public class Common { // connect the database
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String DB_NAME = "test";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
public static final String IP = "192.168.1.103";
public static final String PORT = "3306";
public static final String URL = "jdbc:mysql://" + IP + ":" + PORT + "/" + DB_NAME; // common
public static final String EXCEL_PATH = "lib/student_info.xls"; // sql
public static final String INSERT_STUDENT_SQL = "insert into student_info(no, name, age, score) values(?, ?, ?, ?)";
public static final String UPDATE_STUDENT_SQL = "update student_info set no = ?, name = ?, age= ?, score = ? where id = ? ";
public static final String SELECT_STUDENT_ALL_SQL = "select id,no,name,age,score from student_info";
public static final String SELECT_STUDENT_SQL = "select * from student_info where name like ";
}
/ExcelTest/src/com/b510/excel/ReadExcel.java
/**
*
*/
package com.b510.excel; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.b510.common.Common;
import com.b510.excel.vo.Student; /**
* @author Hongten
* @created 2014-5-18
*/
public class ReadExcel { public List<Student> readXls() throws IOException {
InputStream is = new FileInputStream(Common.EXCEL_PATH);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
Student student = null;
List<Student> list = new ArrayList<Student>();
// 循环工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
student = new Student();
HSSFCell no = hssfRow.getCell(0);
HSSFCell name = hssfRow.getCell(1);
HSSFCell age = hssfRow.getCell(2);
HSSFCell score = hssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
list.add(student);
}
}
}
return list;
} @SuppressWarnings("static-access")
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
// 返回布尔类型的值
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
// 返回数值类型的值
return String.valueOf(hssfCell.getNumericCellValue());
} else {
// 返回字符串类型的值
return String.valueOf(hssfCell.getStringCellValue());
}
}
}
/ExcelTest/src/com/b510/excel/SaveData2DB.java
/**
*
*/
package com.b510.excel; import java.io.IOException;
import java.sql.SQLException;
import java.util.List; import com.b510.common.Common;
import com.b510.excel.util.DbUtil;
import com.b510.excel.vo.Student; /**
* @author Hongten
* @created 2014-5-18
*/
public class SaveData2DB { @SuppressWarnings({ "rawtypes" })
public void save() throws IOException, SQLException {
ReadExcel xlsMain = new ReadExcel();
Student student = null;
List<Student> list = xlsMain.readXls(); for (int i = 0; i < list.size(); i++) {
student = list.get(i);
List l = DbUtil.selectOne(Common.SELECT_STUDENT_SQL + "'%" + student.getName() + "%'", student);
if (!l.contains(1)) {
DbUtil.insert(Common.INSERT_STUDENT_SQL, student);
} else {
System.out.println("The Record was Exist : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + ", and has been throw away!");
}
}
}
}
/ExcelTest/src/com/b510/excel/util/DbUtil.java
/**
*
*/
package com.b510.excel.util; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.b510.common.Common;
import com.b510.excel.vo.Student; /**
* @author Hongten
* @created 2014-5-18
*/
public class DbUtil { /**
* @param sql
*/
public static void insert(String sql, Student student) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName(Common.DRIVER);
conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
ps = conn.prepareStatement(sql);
ps.setString(1, student.getNo());
ps.setString(2, student.getName());
ps.setString(3, student.getAge());
ps.setString(4, String.valueOf(student.getScore()));
boolean flag = ps.execute();
if(!flag){
System.out.println("Save data : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + " succeed!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
} @SuppressWarnings({ "unchecked", "rawtypes" })
public static List selectOne(String sql, Student student) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
try {
Class.forName(Common.DRIVER);
conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
if(rs.getString("no").equals(student.getNo()) || rs.getString("name").equals(student.getName())|| rs.getString("age").equals(student.getAge())){
list.add(1);
}else{
list.add(0);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
return list;
} public static ResultSet selectAll(String sql) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName(Common.DRIVER);
conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
return rs;
} }
/ExcelTest/src/com/b510/excel/vo/Student.java
/**
*
*/
package com.b510.excel.vo; /**
* Student
*
* @author Hongten
* @created 2014-5-18
*/
public class Student {
/**
* id
*/
private Integer id;
/**
* 学号
*/
private String no;
/**
* 姓名
*/
private String name;
/**
* 学院
*/
private String age;
/**
* 成绩
*/
private float score; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getNo() {
return no;
} public void setNo(String no) {
this.no = no;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public float getScore() {
return score;
} public void setScore(float score) {
this.score = score;
} }
源码下载:http://files.cnblogs.com/hongten/ExcelTest.zip
========================================================
多读一些书,英语很重要。
More reading,and english is important.
I'm Hongten

========================================================
java的poi技术读取Excel数据到MySQL的更多相关文章
- java的poi技术读取Excel数据
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- java的poi技术写Excel的Sheet
在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...
- jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL
这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...
- java的poi技术读取和导入Excel实例
本篇文章主要介绍了java的poi技术读取和导入Excel实例,报表输出是Java应用开发中经常涉及的内容,有需要的可以了解一下. 报表输出是Java应用开发中经常涉及的内容,而一般的报表往往缺乏通用 ...
- php+phpspreadsheet读取Excel数据存入mysql
先生成Excel模板,然后导入Excel数据到mysql,每条数据对应图片上传到阿里云 <?php /** * Created by PhpStorm. * User: Administrato ...
- java的poi技术读取和导入Excel
项目结构: http://www.cnblogs.com/hongten/gallery/image/111987.html 用到的Excel文件: http://www.cnblogs.com/h ...
- java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)
使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...
随机推荐
- 简单入门canvas - 通过刮奖效果来学习
一 .前言 一直在做PC端的前端开发,从互联网到行业软件.最近发现移动端已经成为前端必备技能了,真是不能停止学习.HTML5新增的一些东西,canvas是用的比较多也比较复杂的一个,简单的入门了一下, ...
- REST简介
一说到REST,我想大家的第一反应就是“啊,就是那种前后台通信方式.”但是在要求详细讲述它所提出的各个约束,以及如何开始搭建REST服务时,却很少有人能够清晰地说出它到底是什么,需要遵守什么样的准则. ...
- hadoop 2.7.3本地环境运行官方wordcount
hadoop 2.7.3本地环境运行官方wordcount 基本环境: 系统:win7 虚机环境:virtualBox 虚机:centos 7 hadoop版本:2.7.3 本次先以独立模式(本地模式 ...
- Dapper where Id in的解决方案
简单记一下,一会出去有点事情~ 我们一般写sql都是==>update NoteInfo set NDataStatus=@NDataStatus where NId in (@NIds) Da ...
- 【干货分享】流程DEMO-外出申请
流程名: 外出申请 流程相关文件: 流程包.xml 流程说明: 直接导入流程包文件,即可使用本流程 表单: 流程: 图片:2.png DEMO包下载: http://files.cnblog ...
- 08讲browse命令的使用技巧
.浏览所有parts ,使用技巧 .浏览所有 nets,使用技巧 在上图中选择nets .浏览所有 offpage connector,使用技巧 如上 .浏览所有 DRC makers,使用技巧 5. ...
- springMvc的日期转换之二
方式一:使用@InitBinder注解实现日期转换 前台页面: 后台打印: 方式二:处理多种日期格式类型之间的转换 采用方式:由于binder.registerCustomEditor(Date.cl ...
- spring boot1
spring boot 玩转spring boot--快速开始 开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv ...
- Xamarin.Android快速入门
一.准备工作 1.创建一个空的解决方案,并命名为Phoneword 2.右击解决方案 新建->新建项目 并命名为Phoneword_Droid 二.界面 1.打开Resources文件夹-> ...
- c++的性能, c#的产能?!鱼和熊掌可以兼得,.NET NATIVE初窥
对于微软开发者来说,每次BUILD大会都是值得期待的.这次也是惊喜满满,除了大众瞩目的WP8.1的发布还有一项会令开发者兴奋的技术出现:.NET NATIVE.下面就来详细了解一下其为何物. [小九的 ...