POI3.9效率大幅度提高,支持xls以及xlsx。

首先需要POI的JAR包,MAVEN配置如下:

<!-- excel start -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency> <dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency> <dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- excel end -->
          <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency> <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency> <dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5-pre10</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${springversion}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>

ReadExcel.java

package excel;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import mysql.mapper.StudentMapper; 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 org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import Student.Student; public class ReadExcel { private StudentMapper studentMapper; public ReadExcel(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
studentMapper = (StudentMapper) ctx.getBean("studentMapper");
} public List<Student> readExcel(String path) throws IOException {
if (path == null || path.equals("")) {
return null;
}
String postfix = getPostfix(path);
if (!"".equals(postfix)) {
if ("xls".equals(postfix)) {
return readXls(path);
} else if ("xlsx".equals(path)) {
return readXlsx(path);
}
} else {
System.out.println(" : Not the Excel file!");
}
return null;
} public List<Student> readXlsx(String path) throws IOException {
InputStream is = new FileInputStream(path);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
Student student = null;
List<Student> list = new ArrayList<Student>();
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
student = new Student();
XSSFCell no = xssfRow.getCell(0);
XSSFCell name = xssfRow.getCell(1);
XSSFCell age = xssfRow.getCell(2);
XSSFCell score = xssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
studentMapper.insert(student);
list.add(student);
}
}
}
return list;
} public List<Student> readXls(String path) throws IOException {
System.out.println("processing...");
InputStream is = new FileInputStream(path);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
Student student = null;
List<Student> list = new ArrayList<Student>();
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
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)));
studentMapper.insert(student);
list.add(student);
}
}
}
return list;
} @SuppressWarnings("static-access")
private String getValue(XSSFCell xssfRow) {
if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
return String.valueOf(xssfRow.getNumericCellValue());
} else {
return String.valueOf(xssfRow.getStringCellValue());
}
} @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());
}
} public String getPostfix(String path){
if(path == null || path.equals(" ")){
return "";
}
if(path.contains(".")){
return path.substring(path.lastIndexOf(".") + 1, path.length());
}
return "";
}
}

applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置数据源, 整合其他框架, 事务等. -->
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 数据源,使用dbcp -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="minPoolSize" value="${jdbc.miniPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" /> <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" />
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}" />
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" />
<property name="automaticTestTable" value="${jdbc.automaticTestTable}" />
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
<property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" /> </bean> <!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean> <!-- mapper配置 MapperFactoryBean:根据mapper接口生成代理对象,和下面方式二选一 -->
<!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.alibaba.mapper.UserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean> --> <!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册 遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录
中 自动扫描出来的mapper的bean的id为mapper类名(首字母小写) -->
<!-- 指定扫描的包名 如果扫描多个包,每个包中间使用半角逗号分隔 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="station.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean> </beans>

db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/test
jdbc.user = root
jdbc.password = 123456
jdbc.miniPoolSize = 1
jdbc.maxPoolSize = 20
jdbc.initialPoolSize = 1
jdbc.maxIdleTime = 25000
jdbc.acquireIncrement = 1 jdbc.acquireRetryAttempts = 30
jdbc.acquireRetryDelay = 1000
jdbc.testConnectionOnCheckin = true
jdbc.automaticTestTable = c3p0TestTable
jdbc.idleConnectionTestPeriod = 18000
jdbc.checkoutTimeout=3000

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <settings>
<!-- 打开延迟加载 的开关 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 将积极加载改为消极加载即按需要加载 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true" />
</settings> <!-- 别名定义 -->
<typeAliases> <!-- 批量别名定义 指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以) -->
<package name="Student" /> </typeAliases> <!-- 加载 映射文件 -->
<!-- <mappers> -->
<!-- <mapper resource="mybatis/UserMapper.xml" /> --> <!-- 批量加载mapper 指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录
中 上边规范的前提是:使用的是mapper代理方法 和spring整合后,使用mapper扫描器,这里不需要配置了 -->
<!-- <package name="mysql.mapper"/> --> <!-- </mappers> --> </configuration>

测试类:

package client;

import java.io.IOException;
import java.util.List; import Student.Student; import excel.ReadExcel; public class Client { public static void main(String[] args) throws IOException{
List<Student> list = new ReadExcel().readExcel("D:\\student.xls");
if(list != null){
for(Student student:list){
System.out.println(student);
}
}
} }

数据库设计

项目结构:

excel读入数据库的更多相关文章

  1. 一步步实现ABAP后台导入EXCEL到数据库【3】

    在一步步实现ABAP后台导入EXCEL到数据库[2]里,我们已经实现计划后台作业将数据导入数据库的功能.但是,这只是针对一个简单的自定义结构的导入程序.在实践应用中,面对不同的表.不同的导入文件,我们 ...

  2. ASP.NET 将Excel导入数据库

    将Excel导入数据库大致流程:  Excel数据->DataSet->数据库 需要做的准备:1.FileUpload控件一个,按钮一个,如果需要即时显示那么GridView或DataGr ...

  3. 一步步实现ABAP后台导入EXCEL到数据库【1】

    在SAP的应用当中,导入.导出EXCEL文件的情况是一个常见的需求,有时候用户需要将大量数据定期导入到SAP的数据库中.这种情况下,使用导入程序在前台导入可能要花费不少的时间,如果能安排导入程序为后台 ...

  4. Python爬虫爬取豆瓣电影名称和链接,分别存入txt,excel和数据库

    前提条件是python操作excel和数据库的环境配置是完整的,这个需要在python中安装导入相关依赖包: 实现的具体代码如下: #!/usr/bin/python# -*- coding: utf ...

  5. SQLBulkCopy使用实例--读取Excel写入数据库/将 Excel 文件转成 DataTable

    MS SQL Server 提供一个称为 bcp 的流行的命令提示符实用工具,用于将数据从一个表移动到另一个表(表可以在不同服务器上). SqlBulkCopy 类允许编写提供类似功能的托管代码解决方 ...

  6. excel 导入数据库 / SSIS 中 excel data source --64位excel 版本不支持-- solution

    当本地安装的excel(2013版) 是64-bit时:出现的以下两种错误 解决: 1. excel 导入数据库 , 如果文件是2007则会出现:“The 'Microsoft.ACE.OLEDB.1 ...

  7. 如何使用NPOI 导出到excel和导入excel到数据库

    近期一直在做如何将数据库的数据导出到excel和导入excel到数据库. 首先进入官网进行下载NPOI插件(http://npoi.codeplex.com/). 我用的NPOI1.2.5稳定版. 使 ...

  8. Excel 、数据库 一言不合就转换 (zhuan)

    http://blog.csdn.net/marksinoberg/article/details/52280786 ***************************************** ...

  9. Uploadify上传Excel到数据库

    前两章简单的介绍了Uploadify上传插件的基本使用和相关的属性说明.这一章结合Uploadify+ssh框架+jquery实现Excel上传并保存到数据库.         以前写的这篇文章 Jq ...

随机推荐

  1. at org.apache.jsp.index_jsp._jspInit(index_jsp.java:23)异常解决

    部署项目,启动tomcat一切正常.输入项目地址后 tomcat报例如以下错误: java.lang.NullPointerException at org.apache.jsp.index_jsp. ...

  2. Codeforces Round #262 (Div. 2) B

    题目: B. Little Dima and Equation time limit per test 1 second memory limit per test 256 megabytes inp ...

  3. C#操作XML存取创建XML

    using System.Xml; #region 生成XML文档 /// <summary> ///  /// </summary> /// <param name=& ...

  4. C++函数传值调用

    C++的函数的参数调用是传值方式. 想要改变传值调用,有引用和指针两种方式.其中,引用的实现机理也是通过一个指针,但是具体和指针传值的方式又不一样.具体见:C++中的指针与引用 对于指针传值,其实实际 ...

  5. day2_python学习笔记_chapter4_标准类型和内建函数

    1. 标准类型 Integer,Boolean, Long integer, Floating point real number, Complex number, String, List, Tup ...

  6. AXIS2远程调用WebService示例(Eclipse+AXIS)

    转自:http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/10/3071584.html 我们将Web Service发布在Tomcat或者其他应 ...

  7. 常用Android快速开发框架

    在做项目的过程中遇到了很多困难,于是收集了一些快速开发的框架,使用后大大提高了项目开发速度,无论什么项目都可以使用的到,在此分享给大家,希望能对大家有帮助!(个人建议:有时间的同学可以看一下这些优秀框 ...

  8. ECSHOP 开发总结

    今天算是仔细学习ecshop 的第一天,实话说,如果不是任务紧,肯定不用这个东西.2013年之后都不再维护了.使用起来万一出什么BUG 就不好了.而且不是纯粹的MVC ,看代码也是怪怪的呢.但是都已经 ...

  9. MySQL、You are using safe update mode

    MySQL默认模式是sql_safe_updates=1的.在这个模式下不管你是update还是delete一行where 条件都要指定主键.如果where条件只出现的不是主键就会出错. 例子: se ...

  10. qemu/kvm/qemu-kvm/virsh的区别

    转自:http://www.2cto.com/os/201305/209596.html qemu/kvm/qemu-kvm/virsh的区别   qemu是一套虚拟机管理系统,kqemu是qemu的 ...