里面都是我自己的业务逻辑,需要的话可以把业务逻辑换成自己的
1.所需要的工具类
package com.zknw.poi;
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 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.web.multipart.MultipartFile;
public class ExcelRead {
public int totalRows; //sheet中总行数
public static int totalCells; //每一行总单元格数
/**
* read the Excel .xlsx,.xls
* @param file jsp中的上传文件
* @return
* @throws IOException
*/
public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
return null;
}else{
String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
if(!ExcelUtil.EMPTY.equals(postfix)){
if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
}
/**
* read the Excel 2010 .xlsx
* @param file
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXlsx(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//读取Row,从第三行开始
for(int rowNum = 2;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (Throwable e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
/**
* read the Excel 2003-2007 .xls
* @param file
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXls(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new HSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//读取Row,从第三行开始
for(int rowNum = 2;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//读取列,从第一列开始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (Throwable e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
}
package com.zknw.poi;
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 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.web.multipart.MultipartFile;
public class ExcelRead {
public int totalRows; //sheet中总行数
public static int totalCells; //每一行总单元格数
/**
* read the Excel .xlsx,.xls
* @param file jsp中的上传文件
* @return
* @throws IOException
*/
public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
return null;
}else{
String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
if(!ExcelUtil.EMPTY.equals(postfix)){
if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
}
/**
* read the Excel 2010 .xlsx
* @param file
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXlsx(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//读取Row,从第三行开始
for(int rowNum = 2;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (Throwable e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
/**
* read the Excel 2003-2007 .xls
* @param file
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXls(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new HSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//读取Row,从第三行开始
for(int rowNum = 2;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//读取列,从第一列开始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (Throwable e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
}
2.controller接口,里面是我自己的业务逻辑
/**
* excel文件的上传
*/
@RequestMapping(value="/uploadExcel/schemeId/{schemeId}/multipleValue/{multipleValue}",method=RequestMethod.POST)
public void uploadFiles(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") MultipartFile file, @PathVariable Integer schemeId, @PathVariable Boolean multipleValue){
//读取Excel数据到List中
try {
List<String> strs = new ArrayList<>();
List<ArrayList<String>> list = new ExcelRead().readExcel(file);
//list中存的就是excel中的数据,可以根据excel中每一列的值转换成你所需要的值(从0开始)
BasicFault basicFault = null;
List<BasicFault> lisebasicFault = new ArrayList<BasicFault>();
int j = 1;
int a = 1;
for(ArrayList<String> arr : list){
if(arr.get(0)!=null&&!arr.get(0).toString().equals("")){
basicFault = new BasicFault();
if (arr.get(2)!=null && !arr.get(2).isEmpty()){
//查询并且添加主部件信息
BasicTurbComponent basicTurbComponent = basicTurbComponentService.selectbasicturbcomponent(arr.get(2));
if (basicTurbComponent!=null && basicTurbComponent.getTurbComponentName()!= null && !basicTurbComponent.getTurbComponentName().isEmpty()){
//直接取出ID来
basicFault.setTurbComponentId(basicTurbComponent.getTurbComponentId());
}else {
//先进行添加,然后再把ID取出来
if (arr.get(2)!=null && !arr.get(2).isEmpty()){
basicTurbComponentService.addTurbComponent(arr.get(2));
BasicTurbComponent basicTurbComponent111 = basicTurbComponentService.selectbasicturbcomponent(arr.get(2));
basicFault.setTurbComponentId(basicTurbComponent111.getTurbComponentId());
}
}
}
if (arr.get(2)!=null && !arr.get(2).isEmpty()){
//查询并且添加分部件信息
BasicTurbComponent basicsubcomponentids = basicTurbComponentService.selectbasicsubcomponentids(arr.get(2),arr.get(3));
if (basicsubcomponentids!=null && basicsubcomponentids.getTurbComponentName()!=null &&!basicsubcomponentids.getTurbComponentName().isEmpty()){
//直接取出ID来
basicFault.setSubComponentIds(Integer.toString(basicsubcomponentids.getTurbComponentId()));
}else {
//先查询一级菜单对应的ID,把ID取出来,添加到二级菜单的parentid
BasicTurbComponent yijiid = basicTurbComponentService.selectbasicturbcomponent(arr.get(2));
Integer parentId = yijiid.getTurbComponentId();
Map<String,Object> map = new HashMap<String, Object>();
map.put("parentId",parentId);
if (arr.get(3) !=null && !arr.get((3)).isEmpty()){
map.put("turbComponentName",arr.get(3));
basicTurbComponentService.adderji(map);
BasicTurbComponent subcomponentids = basicTurbComponentService.selectbasicsubcomponentids(arr.get(2),arr.get(3));
basicFault.setSubComponentIds(Integer.toString(subcomponentids.getTurbComponentId()));
}
}
}
//查询并且添加子部件信息
if (arr.get(3)!=null && !arr.get(3).isEmpty()){
BasicTurbComponent basicpartsids = basicTurbComponentService.selectbasicpartsids(arr.get(2),arr.get(3),arr.get(4));
if (basicpartsids!=null && basicpartsids.getTurbComponentName()!=null && !basicpartsids.getTurbComponentName().isEmpty()){
//直接取出ID来
basicFault.setPartsIds(Integer.toString(basicpartsids.getTurbComponentId()));
}else {
//先查询二级菜单对应的ID,把ID取出来,添加到三级菜单的parentid
BasicTurbComponent erjiid = basicTurbComponentService.selectbasicsubcomponentids(arr.get(2),arr.get(3));
Integer parentId = erjiid.getTurbComponentId();
Map<String,Object> map = new HashMap<String,Object>();
map.put("parentId",parentId);
if (arr.get(4) !=null && !arr.get((4)).isEmpty()){
map.put("turbComponentName",arr.get(4));
basicTurbComponentService.addsanji(map);
BasicTurbComponent partsids = basicTurbComponentService.selectbasicpartsids(arr.get(2),arr.get(3),arr.get(4));
basicFault.setPartsIds(Integer.toString(partsids.getTurbComponentId()));
}
}
}
boolean flag = true;
if (multipleValue==true && arr.get(5)!=null && !arr.get(5).isEmpty()){
BasicTag basicTag = basicTagService.selectagid(arr.get(5));
if (basicTag!=null){
basicFault.setTagId(basicTag.getTagId());
}else {
strs.add(arr.get(5));
strs.add(arr.get(1));
flag = false;
}
}else {
basicFault.setTagId(487);
}
basicFault.setSchemeId(schemeId);
basicFault.setFaultCode(Integer.parseInt(arr.get(0)));
basicFault.setFaultLevelId(1);
basicFault.setFaultDesc(arr.get(1));
basicFault.setAlarmCategoryId(1);
basicFault.setFaultSeq(a++);
BasicFault b = basicFaultService.selectfault(basicFault);
if (b == null && flag == true){
basicFaultService.add(basicFault);
}
}
j++;
}
retBases(request, response, new ResultData(Code.SUCCESS, "Excel导入成功", strs));
} catch (Exception e) {
e.printStackTrace();
retBases(request, response, new ResultData(Code.ERROR, "请查看Excel格式是否正确", e.getMessage()));
}
}
3.service接口
package com.zknw.basicmanage.api;
import com.zknw.basicmanage.model.BasicFault;
import com.zknw.basicmanage.model.BasicScheme;
import com.zknw.poi.JsonBean;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
/**
* 故障
* Created by Administrator on 2017/7/18.
*/
public interface BasicFaultService {
/**
* 批量插入数据
* @param file
* @return
*/
int insertBasicFaultList(List<BasicFault> lisebasicFault);
void add(BasicFault basicFault);
BasicFault selectfault(BasicFault basicFault);
}
4.service实现类
package com.zknw.basicmanage.impl;
import com.zknw.basicmanage.api.BasicFaultService;
import com.zknw.basicmanage.api.BasicTurbComponentService;
import com.zknw.basicmanage.dao.BasicFaultDao;
import com.zknw.basicmanage.model.BasicFault;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 故障
* Created by Administrator on 2017/7/18.
*/
@Service("basicFaultService")
public class BasicFaultServiceImpl implements BasicFaultService{
@Resource
private BasicFaultDao basicFaultDao;
@Resource
private BasicTurbComponentService basicTurbComponentService;
private static final Logger logger = Logger.getLogger(BasicFaultServiceImpl.class);
@Override
public int insertBasicFaultList(List<BasicFault> lisebasicFault) {
return basicFaultDao.insertBasicFaultList(lisebasicFault);
}
@Override
public void add(BasicFault basicFault) {
basicFaultDao.add(basicFault);
}
@Override
public BasicFault selectfault(BasicFault basicFault) {
try{
Map<String,Object> map=new HashMap<String,Object>();
map.put("faultCode", basicFault.getFaultCode());
map.put("schemeId", basicFault.getSchemeId());
map.put("alarmCategoryId", basicFault.getAlarmCategoryId());
return basicFaultDao.selectfault(map);
}catch (Exception e){
logger.info("故障服务",new Throwable(e.getMessage()));
throw e;
}
}
}
5.dao的接口
package com.zknw.basicmanage.dao;
import com.zknw.basicmanage.model.BasicFault;
import com.zknw.basicmanage.model.BasicScheme;
import com.zknw.util.BaseDAO;
import java.util.List;
import java.util.Map;
/**
* 故障
* Created by Administrator on 2017/7/18.
*/
public interface BasicFaultDao extends BaseDAO<BasicFault> {
int insertBasicFaultList(List<BasicFault> lisebasicFault);
void add(BasicFault basicFault);
BasicFault selectfault(Map<String, Object> map);
}
6.mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zknw.basicmanage.dao.BasicFaultDao" >
<resultMap id="BasicFarmMap" type="com.zknw.basicmanage.model.BasicFault" >
<id column="faultid" property="faultId" jdbcType="BIGINT" />
<result column="schemeid" property="schemeId" jdbcType="BIGINT" />
<result column="faultcode" property="faultCode" jdbcType="VARCHAR" />
<result column="faultlevelid" property="faultLevelId" jdbcType="BIGINT" />
<result column="tagid" property="tagId" jdbcType="BIGINT" />
<result column="unalarm" property="unAlarm" jdbcType="BIT" />
<result column="faultdesc" property="faultDesc" jdbcType="VARCHAR" />
<result column="faultseq" property="faultSeq" jdbcType="BIGINT" />
<result column="alarmcategoryid" property="alarmCategoryId" jdbcType="VARCHAR" />
<result column="turbcomponentid" property="turbComponentId" jdbcType="BIGINT" />
<result column="partsids" property="partsIds" jdbcType="VARCHAR" />
<result column="subcomponentids" property="subComponentIds" jdbcType="VARCHAR" />
</resultMap>
<!--批量添加数据-->
<insert id="insertBasicFaultList" parameterType="java.util.List" >
insert into basic_fault (schemeid, faultcode, faultlevelid, tagid, unalarm, faultdesc, faultseq, alarmcategoryid, turbcomponentid, subcomponentids, partsids )
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.schemeid}, #{item.faultcode}, #{item.faultlevelid}, #{item.tagid}, 't', #{item.faultdesc},
#{item.faultseq}, #{item.alarmcategoryid}, #{item.turbcomponentid}, #{item.subcomponentids}, #{item.partsids})
</foreach>
</insert>
<insert id="add" parameterType="com.zknw.basicmanage.model.BasicFault" >
INSERT INTO basic_fault (schemeid, faultcode, faultlevelid, tagid, unalarm, faultdesc, faultseq, alarmcategoryid, turbcomponentid, subcomponentids, partsids )
VALUES
(#{schemeId}, #{faultCode}, #{faultLevelId}, #{tagId}, 't', #{faultDesc}, #{faultSeq}, #{alarmCategoryId}, #{turbComponentId}, #{subComponentIds}, #{partsIds})
</insert>
<select id="selectfault" resultType="com.zknw.basicmanage.model.BasicFault" parameterType="java.util.Map">
select * from basic_fault WHERE faultcode = #{faultCode} and schemeid = #{schemeId} and alarmcategoryid = #{alarmCategoryId}
</select>
</mapper>
7.前台页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js" ></script>
</head>
<body>
<!--<form id="daoru" action="/webapi/v1/faults/uploadExcel" enctype="multipart/form-data" method="post">
选择文件:<input type="file" name="file">
<input type="submit" value="提交" />
</form>-->
<form id="uploadForm" enctype="multipart/form-data" method="post">
<p>上传文件:<input type="file" name="file" /></p>
<input type="button" value="上传" onclick="upload()" />
</form>
</body>
<script type="text/javascript">
function upload() {
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: '/webapi/v1/faults/uploadExcel/schemeId/152/multipleValue/false',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
},
error: function(data) {
}
});
}
</script>
</html>
8.所需要的jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<!-- Commons Collections -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.3</version>
</dependency>