java导入excel数据到mysql_java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中。
你也可以在 :
项目结构:
Excel中的测试数据:
数据库结构:
对应的SQL:
1 CREATE TABLE`student_info` (
2 `id` int(11) NOT NULLAUTO_INCREMENT,
3 `no` varchar(20) DEFAULT NULL,
4 `name` varchar(20) DEFAULT NULL,
5 `age` varchar(10) DEFAULT NULL,
6 `score` float DEFAULT '0',
7 PRIMARY KEY(`id`)
8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入数据成功:
如果重复数据,则丢掉:
=============================================
源码部分:
=============================================
/ExcelTest/src/com/b510/client/Client.java
1 /**
2 *
3 */
4 packagecom.b510.client;
5
6 importjava.io.IOException;
7 importjava.sql.SQLException;
8
9 importcom.b510.excel.SaveData2DB;
10
11 /**
12 * @authorHongten
13 * @created 2014-5-18
14 */
15 public classClient {
16
17 public static void main(String[] args) throwsIOException, SQLException {
18 SaveData2DB saveData2DB = newSaveData2DB();
19 saveData2DB.save();
20 System.out.println("end");
21 }
22 }
/ExcelTest/src/com/b510/common/Common.java
1 /**
2 *
3 */
4 packagecom.b510.common;
5
6 /**
7 * @authorHongten
8 * @created 2014-5-18
9 */
10 public classCommon {
11
12 //connect the database
13 public static final String DRIVER = "com.mysql.jdbc.Driver";
14 public static final String DB_NAME = "test";
15 public static final String USERNAME = "root";
16 public static final String PASSWORD = "root";
17 public static final String IP = "192.168.1.103";
18 public static final String PORT = "3306";
19 public static final String URL = "jdbc:mysql://" + IP + ":" + PORT + "/" +DB_NAME;
20
21 //common
22 public static final String EXCEL_PATH = "lib/student_info.xls";
23
24 //sql
25 public static final String INSERT_STUDENT_SQL = "insert into student_info(no, name, age, score) values(?, ?, ?, ?)";
26 public static final String UPDATE_STUDENT_SQL = "update student_info set no = ?, name = ?, age= ?, score = ? where id = ? ";
27 public static final String SELECT_STUDENT_ALL_SQL = "select id,no,name,age,score from student_info";
28 public static final String SELECT_STUDENT_SQL = "select * from student_info where name like ";
29 }
/ExcelTest/src/com/b510/excel/ReadExcel.java
1 /**
2 *
3 */
4 packagecom.b510.excel;
5
6 importjava.io.FileInputStream;
7 importjava.io.IOException;
8 importjava.io.InputStream;
9 importjava.util.ArrayList;
10 importjava.util.List;
11
12 importorg.apache.poi.hssf.usermodel.HSSFCell;
13 importorg.apache.poi.hssf.usermodel.HSSFRow;
14 importorg.apache.poi.hssf.usermodel.HSSFSheet;
15 importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
16
17 importcom.b510.common.Common;
18 importcom.b510.excel.vo.Student;
19
20 /**
21 * @authorHongten
22 * @created 2014-5-18
23 */
24 public classReadExcel {
25
26 public List readXls() throwsIOException {
27 InputStream is = newFileInputStream(Common.EXCEL_PATH);
28 HSSFWorkbook hssfWorkbook = newHSSFWorkbook(is);
29 Student student = null;
30 List list = new ArrayList();
31 //循环工作表Sheet
32 for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
33 HSSFSheet hssfSheet =hssfWorkbook.getSheetAt(numSheet);
34 if (hssfSheet == null) {
35 continue;
36 }
37 //循环行Row
38 for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
39 HSSFRow hssfRow =hssfSheet.getRow(rowNum);
40 if (hssfRow != null) {
41 student = newStudent();
42 HSSFCell no = hssfRow.getCell(0);
43 HSSFCell name = hssfRow.getCell(1);
44 HSSFCell age = hssfRow.getCell(2);
45 HSSFCell score = hssfRow.getCell(3);
46 student.setNo(getValue(no));
47 student.setName(getValue(name));
48 student.setAge(getValue(age));
49 student.setScore(Float.valueOf(getValue(score)));
50 list.add(student);
51 }
52 }
53 }
54 returnlist;
55 }
56
57 @SuppressWarnings("static-access")
58 privateString getValue(HSSFCell hssfCell) {
59 if (hssfCell.getCellType() ==hssfCell.CELL_TYPE_BOOLEAN) {
60 //返回布尔类型的值
61 returnString.valueOf(hssfCell.getBooleanCellValue());
62 } else if (hssfCell.getCellType() ==hssfCell.CELL_TYPE_NUMERIC) {
63 //返回数值类型的值
64 returnString.valueOf(hssfCell.getNumericCellValue());
65 } else{
66 //返回字符串类型的值
67 returnString.valueOf(hssfCell.getStringCellValue());
68 }
69 }
70 }
/ExcelTest/src/com/b510/excel/SaveData2DB.java
1 /**
2 *
3 */
4 packagecom.b510.excel;
5
6 importjava.io.IOException;
7 importjava.sql.SQLException;
8 importjava.util.List;
9
10 importcom.b510.common.Common;
11 importcom.b510.excel.util.DbUtil;
12 importcom.b510.excel.vo.Student;
13
14 /**
15 * @authorHongten
16 * @created 2014-5-18
17 */
18 public classSaveData2DB {
19
20 @SuppressWarnings({ "rawtypes"})
21 public void save() throwsIOException, SQLException {
22 ReadExcel xlsMain = newReadExcel();
23 Student student = null;
24 List list =xlsMain.readXls();
25
26 for (int i = 0; i < list.size(); i++) {
27 student =list.get(i);
28 List l = DbUtil.selectOne(Common.SELECT_STUDENT_SQL + "'%" + student.getName() + "%'", student);
29 if (!l.contains(1)) {
30 DbUtil.insert(Common.INSERT_STUDENT_SQL, student);
31 } else{
32 System.out.println("The Record was Exist : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + ", and has been throw away!");
33 }
34 }
35 }
36 }
/ExcelTest/src/com/b510/excel/util/DbUtil.java
1 /**
2 *
3 */
4 packagecom.b510.excel.util;
5
6 importjava.sql.Connection;
7 importjava.sql.DriverManager;
8 importjava.sql.PreparedStatement;
9 importjava.sql.ResultSet;
10 importjava.sql.SQLException;
11 importjava.util.ArrayList;
12 importjava.util.List;
13
14 importcom.b510.common.Common;
15 importcom.b510.excel.vo.Student;
16
17 /**
18 * @authorHongten
19 * @created 2014-5-18
20 */
21 public classDbUtil {
22
23 /**
24 * @paramsql
25 */
26 public static void insert(String sql, Student student) throwsSQLException {
27 Connection conn = null;
28 PreparedStatement ps = null;
29 try{
30 Class.forName(Common.DRIVER);
31 conn =DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
32 ps =conn.prepareStatement(sql);
33 ps.setString(1, student.getNo());
34 ps.setString(2, student.getName());
35 ps.setString(3, student.getAge());
36 ps.setString(4, String.valueOf(student.getScore()));
37 boolean flag =ps.execute();
38 if(!flag){
39 System.out.println("Save data : No. = " + student.getNo() + " , Name = " + student.getName() + ", Age = " + student.getAge() + " succeed!");
40 }
41 } catch(Exception e) {
42 e.printStackTrace();
43 } finally{
44 if (ps != null) {
45 ps.close();
46 }
47 if (conn != null) {
48 conn.close();
49 }
50 }
51 }
52
53 @SuppressWarnings({ "unchecked", "rawtypes"})
54 public static List selectOne(String sql, Student student) throwsSQLException {
55 Connection conn = null;
56 PreparedStatement ps = null;
57 ResultSet rs = null;
58 List list = newArrayList();
59 try{
60 Class.forName(Common.DRIVER);
61 conn =DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
62 ps =conn.prepareStatement(sql);
63 rs =ps.executeQuery();
64 while(rs.next()){
65 if(rs.getString("no").equals(student.getNo()) || rs.getString("name").equals(student.getName())|| rs.getString("age").equals(student.getAge())){
66 list.add(1);
67 }else{
68 list.add(0);
69 }
70 }
71 } catch(Exception e) {
72 e.printStackTrace();
73 } finally{
74 if (rs != null) {
75 rs.close();
76 }
77 if (ps != null) {
78 ps.close();
79 }
80 if (conn != null) {
81 conn.close();
82 }
83 }
84 return list;
85 }
86
87
88 public static ResultSet selectAll(String sql) throws SQLException {
89 Connection conn = null;
90 PreparedStatement ps = null;
91 ResultSet rs = null;
92 try {
93 Class.forName(Common.DRIVER);
94 conn = DriverManager.getConnection(Common.URL, Common.USERNAME, Common.PASSWORD);
95 ps = conn.prepareStatement(sql);
96 rs = ps.executeQuery();
97 } catch (Exception e) {
98 e.printStackTrace();
99 } finally {
100 if (rs != null) {
101 rs.close();
102 }
103 if (ps != null) {
104 ps.close();
105 }
106 if (conn != null) {
107 conn.close();
108 }
109 }
110 return rs;
111 }
112
113 }
/ExcelTest/src/com/b510/excel/vo/Student.java
1 /**
2 *
3 */
4 packagecom.b510.excel.vo;
5
6 /**
7 * Student
8 *
9 * @authorHongten
10 * @created 2014-5-18
11 */
12 public classStudent {
13 /**
14 * id
15 */
16 privateInteger id;
17 /**
18 * 学号
19 */
20 privateString no;
21 /**
22 * 姓名
23 */
24 privateString name;
25 /**
26 * 学院
27 */
28 privateString age;
29 /**
30 * 成绩
31 */
32 private floatscore;
33
34 publicInteger getId() {
35 returnid;
36 }
37
38 public voidsetId(Integer id) {
39 this.id =id;
40 }
41
42 publicString getNo() {
43 returnno;
44 }
45
46 public voidsetNo(String no) {
47 this.no =no;
48 }
49
50 publicString getName() {
51 returnname;
52 }
53
54 public voidsetName(String name) {
55 this.name =name;
56 }
57
58 publicString getAge() {
59 returnage;
60 }
61
62 public voidsetAge(String age) {
63 this.age =age;
64 }
65
66 public floatgetScore() {
67 returnscore;
68 }
69
70 public void setScore(floatscore) {
71 this.score =score;
72 }
73
74 }
转载:http://www.cnblogs.com/hongten/p/java_poi_excel.html
java导入excel数据到mysql_java的poi技术读取Excel数据到MySQL相关推荐
- poi excel mysql_java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 :java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 : ...
- java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 读取excel和MySQL相关: ja ...
- java读取excel2010文件_java的poi技术读取Excel[2003-2007,2010]
这篇blog主要是讲述java中poi读取excel,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx. 你也可以在 : 下面是本文的项目结构: ...
- 使用POI技术往Excel中写入图片并以附件的形式发送给对方
使用POI技术往Excel中写入图片 Service层代码 fastDFS工具类 ExcelUtil工具类 Service层代码 @Service public class UserChangeSer ...
- vb.net读取excel并写入dgv_如何用Python读取Excel中的图片?然后写入图片?
大家好,在使用Python进行办公自动化操作时,一定少不了与Excel表格的交互,我们通常是用pandas处理表格数据,但大多数情况下,都是读取表格中的数值进行分析. 那么你知道如何使用Python读 ...
- 【操作系统】磁盘转速速度为7200PRM,平均寻道时间为6ms,每磁道存储1MB数据。如果数据块大小为4KB,则读取一块数据时,数据平均传输速率为
磁盘转速速度为7200PRM,平均寻道时间为6ms,每磁道存储1MB数据.如果数据块大小为4KB,则读取一块数据时,数据平均传输速率为 背景知识 7200PRM = 7200r/min = 120r/ ...
- Java的poi技术读取和导入Excel
2019独角兽企业重金招聘Python工程师标准>>> 项目结构: 用到的Excel文件: XlsMain .java 类 //该类有main方法,主要负责运行程序,同时该类中也包含 ...
- java通过POI快速读取excel大量数据的方式
1.在pom.xml中引入poi相关依赖 <dependency><groupId>cn.afterturn</groupId><artifactId> ...
- java读取excel数据的方法是_java怎么读取excel文件里的数据
展开全部 下面是一个简单的读取例子,如果报"java.io.IOException: Invalid header signature; read 4503608217567241, exp ...
最新文章
- “向前进,向钱进”上:自媒体的流量变现路
- 基于stm32、spi协议的Fatfs文件系统移植(附完整代码下载)
- 服务器能进系统滴滴响,曙光服务器开机滴滴响
- 《Java 核心技术卷1 第10版》学习笔记------ -理解方法调用【重载解析、静态绑定、动态绑定】
- 深度解密Go语言之scheduler
- Aho-Corasick automaton 模板
- 【操作系统】操作系统的设计与实现
- PyTorch的学习笔记
- oracle 10g 安装到登录
- Spring源码解析 - BeanFactory接口体系解读
- python dict排序
- 位说法的由来_南方土地庙有榕树的原因,为何会有榕树不容人的说法?
- MySQL数据库约束(非空,唯一,默认,主键,外键约束)
- 计算二叉树叶子结点数
- 计算机水平考试模块数量,职称计算机考试科目、模块数量是什么
- 万娟 白话大数据和机械学习_白话大数据与机器学习
- 2020年专业408的算法题
- 电脑如何进入bios
- 【已解决】LaTeX 调整段落之间的间距 (包含:只调整某一个section或者subsection中的段落间距)
- Mencoder转换视频
热门文章
- 汉诺塔的java实现及一种思路
- mysql数据库乱码检查项
- 一个能让html标签变成文本的html标签lt;xmpgt;
- 作文未来的计算机医生300字,医生作文300字【3篇】
- 对象序列化与反序列化(二进制 byte[])
- @Target({ElementType.METHOD, ElementType.TYPE})
- Win10专业版下如何禁用Windows Defender功能?
- oracle中rownum的三种分页方式
- IDEA上传本地项目到SVN
- JavaScript(九):JavaScript中的内置对象