里面都是我自己的业务逻辑,需要的话可以把业务逻辑换成自己的
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.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.xssf.usermodel.XSSFCell; public class ExcelUtil { public static final String OFFICE_EXCEL_2003_POSTFIX = "xls"; public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx"; public static final String EMPTY = ""; public static final String POINT = "."; public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); / * 获得path的后缀名 * @param path * @return */ public static String getPostfix(String path){ if(path==null || EMPTY.equals(path.trim())){ return EMPTY; } if(path.contains(POINT)){ return path.substring(path.lastIndexOf(POINT)+1,path.length()); } return EMPTY; } / * 单元格格式 * @param hssfCell * @return */ @SuppressWarnings({ "static-access", "deprecation" }) public static String getHValue(HSSFCell hssfCell){ if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) { return String.valueOf(hssfCell.getBooleanCellValue()); } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) { String cellValue = ""; if(HSSFDateUtil.isCellDateFormatted(hssfCell)){ Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue()); cellValue = sdf.format(date); }else{ DecimalFormat df = new DecimalFormat("#."); cellValue = df.format(hssfCell.getNumericCellValue()); String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length()); if(strArr.equals("00")){ cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT)); } } return cellValue; } else { return String.valueOf(hssfCell.getStringCellValue()); } } / * 单元格格式 * @param xssfCell * @return */ public static String getXValue(XSSFCell xssfCell){ if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { return String.valueOf(xssfCell.getBooleanCellValue()); } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) { String cellValue = ""; if(XSSFDateUtil.isCellDateFormatted(xssfCell)){ Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue()); cellValue = sdf.format(date); }else{ DecimalFormat df = new DecimalFormat("#."); cellValue = df.format(xssfCell.getNumericCellValue()); String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length()); if(strArr.equals("00")){ cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT)); } } return cellValue; } else { return String.valueOf(xssfCell.getStringCellValue()); } } static class XSSFDateUtil extends DateUtil{ protected static int absoluteDay(Calendar cal, boolean use1904windowing) { return DateUtil.absoluteDay(cal, use1904windowing); } } }
2.controller接口,里面是我自己的业务逻辑
package com.zknw.basicmanage.controller; import com.zknw.basicmanage.api.BasicFaultService; import com.zknw.basicmanage.api.BasicTagService; import com.zknw.basicmanage.api.BasicTurbComponentService; import com.zknw.basicmanage.model.BasicFault; import com.zknw.basicmanage.model.BasicTag; import com.zknw.basicmanage.model.BasicTurbComponent; import com.zknw.constant.Code; import com.zknw.poi.ExcelRead; import com.zknw.sysmanage.controller.BaseController; import com.zknw.util.ResultData; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; / * 故障 * Created by Administrator on 2017/7/18. * @author yk */ @RestController @RequestMapping(value = "${versionPath}/faults",produces="text/plain; charset=UTF-8") public class BasicFaultController extends BaseController { @Autowired private BasicFaultService basicFaultService; @Resource private BasicTurbComponentService basicTurbComponentService; @Resource private BasicTagService basicTagService; @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>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/102828.html