解决如何使用layui导入Excel表数据
1.前端页面html代码展示
<button type="button" lay-submit="" class="layui-btn layui-btn-warm" lay- filter="uploadImg">
<i class="layui-icon"></i>导出Excel
</button>
2.前端页面js代码展示
layui.use(['table', 'form', 'layer', 'vip_table',"element", "laypage", "upload"], function () {
var form = layui.form
, table = layui.table
, layer = layui.layer
, vipTable = layui.vip_table
, $ = layui.jquery;
var element = layui.element;
var laypage = layui.laypage;
var upload = layui.upload;
upload.render({
elem: '#importData'
,url: '${pageContext.request.contextPath }/infoSheet/ajaxUpload'
,auto: true
,accept: 'file'
,done: function(res){
console.log(res)
if(res.code > 0){
return layer.msg("导入失败",{icon:5,time:1000});
}
return layer.msg("导入成功",{icon:6,time:1000});
}
});
});
3.java后台代码
@ResponseBody
@RequestMapping(value="/ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})
public Map<String, Object> ajaxUploadExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("进来了");
Map<String, Object> map = new HashMap<String, Object>();
String aa= infoSheetService.ajaxUploadExcel(file, request, response);
if("success".equals(aa))
{
map.put("code", 0);
map.put("msg", "success");
}
else {
map.put("code", 1);
map.put("msg", "fail");
}
return map;
}
public String ajaxUploadExcel(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
if(file.isEmpty()){
try {
throw new Exception("文件不存在!");
} catch (Exception e) {
e.printStackTrace();
}
}
InputStream in =null;
try {
in = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
List<List<Object>> listob = null;
try {
listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < listob.size(); i++) {
List<Object> lo = listob.get(i);
InfoSheet vo = new InfoSheet();
InfoSheet j = null;
try {
HashMap<Object, Object> map=new HashMap<Object, Object>();
map.put("infoName", String.valueOf(lo.get(0)));
j = infoSheetMapper.selectByPrimaryKey1(map);
} catch (NumberFormatException e) {
System.out.println("没有新增");
return "fail";
}
vo.setInfoName(String.valueOf(lo.get(0)));
IndustryType industryType=industryTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(1)));
if(industryType==null)
{ IndustryType industryType0=new IndustryType();
industryType0.setIndustryTypeName(String.valueOf(lo.get(1)));
industryTypeMapper.insert(industryType0);
IndustryType industryType1=industryTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(1)));
vo.setIndustryType(industryType1);
}else {
vo.setIndustryType(industryType);
}
InfoType infoType =infoTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(2)));
if (infoType==null) {
InfoType infoType0 =new InfoType();
infoType0.setInfoTypeName(String.valueOf(lo.get(2)));
infoTypeMapper.insert(infoType0);
InfoType infoType1 =infoTypeMapper.selectByPrimaryKey1(String.valueOf(lo.get(2)));
vo.setInfoType(infoType1);
} else {
vo.setInfoType(infoType);
}
Area area=areaMapper.selectByPrimaryKey1(String.valueOf(lo.get(3)));
if (area==null) {
Area area0=new Area();
area0.setAreaName(String.valueOf(lo.get(3)));
areaMapper.insert(area0);
Area area1=areaMapper.selectByPrimaryKey1(String.valueOf(lo.get(3)));
vo.setArea(area1);
} else {
vo.setArea(area);
}
vo.setInfoGround(String.valueOf(lo.get(4)));
vo.setRegistCapital(String.valueOf(lo.get(5)));
vo.setInfoPhone(String.valueOf(lo.get(6)));
vo.setInfoPostbox(String.valueOf(lo.get(7)));
Date infoTime;
try {
String infoString=String.valueOf(lo.get(8)).replace(".", "-");
if("20114-04-14".equals(infoString))
{
System.out.println("i================"+i);
}
String info=infoString+" 00:00:00";
infoTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(info);
vo.setInfoTime(infoTime);
} catch (ParseException e) {
e.printStackTrace();
}
if(j == null)
{
infoSheetMapper.insert(vo);
}
else
{
infoSheetMapper.updateByPrimaryKey(vo);
}
}
return "success";
}
package com.tools;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private final static String excel2003L =".xls";
private final static String excel2007U =".xlsx";
public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
List<List<Object>> list = null;
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(this.getValue(cell));
}
list.add(li);
}
}
return list;
}
public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr);
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr);
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
public String getValue(Cell cell) {
String value = "";
if(null==cell){
return value;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
value = format.format(date);;
}else {
BigDecimal big=new BigDecimal(cell.getNumericCellValue());
value = big.toString();
if(null!=value&&!"".equals(value.trim())){
String[] item = value.split("[.]");
if(1<item.length&&"0".equals(item[1])){
value=item[0];
}
}
}
break;
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue().toString();
break;
case Cell.CELL_TYPE_FORMULA:
value = String.valueOf(cell.getNumericCellValue());
if (value.equals("NaN")) {
value = cell.getStringCellValue().toString();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = " "+ cell.getBooleanCellValue();
break;
default:
value = cell.getStringCellValue().toString();
}
if("null".endsWith(value.trim())){
value="";
}
return value;
}
}
package com.pojo;
import java.util.Date;
public class InfoSheet {
private Integer infoId;
private IndustryType industryType;
private InfoType infoType;
private String infoName;
private String infoGround;
private String registCapital;
private String infoPhone;
private String infoPostbox;
private Date infoTime;
public Integer getInfoId() {
return infoId;
}
private Area area;
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public void setInfoId(Integer infoId) {
this.infoId = infoId;
}
public IndustryType getIndustryType() {
return industryType;
}
public void setIndustryType(IndustryType industryType) {
this.industryType = industryType;
}
public InfoType getInfoType() {
return infoType;
}
public void setInfoType(InfoType infoType) {
this.infoType = infoType;
}
public String getInfoName() {
return infoName;
}
public void setInfoName(String infoName) {
this.infoName = infoName;
}
public String getInfoGround() {
return infoGround;
}
public void setInfoGround(String infoGround) {
this.infoGround = infoGround;
}
public String getRegistCapital() {
return registCapital;
}
public void setRegistCapital(String registCapital) {
this.registCapital = registCapital;
}
public String getInfoPhone() {
return infoPhone;
}
public void setInfoPhone(String infoPhone) {
this.infoPhone = infoPhone;
}
public String getInfoPostbox() {
return infoPostbox;
}
public void setInfoPostbox(String infoPostbox) {
this.infoPostbox = infoPostbox;
}
public Date getInfoTime() {
return infoTime;
}
public void setInfoTime(Date infoTime) {
this.infoTime = infoTime;
}
}
4.感谢你的浏览访问
工作几年,略有心得,然很少整理成文,平常工作中浏览了不少道友的好文章,受益良多。
顾也开始写一些文章, 希望能与各位道友分享进步 !!!!
如果有用,欢迎各位点赞评论,若有不足,亦可指正!!!