由于我个人电脑装的Excel是2016版本的,所以这地方我使用了XSSF 方式导入 。

1先手要制定一个Excel 模板 把模板放入javaWeb工程的某一个目录下如图:

2模板建好了后,先实现模板下载功能 下面是页面jsp代码在这里只贴出部分代码

<!-- excel 导入小模块窗口  -->
<div id="importBox" class="" style="display: none;">
<form id="importForm" action="<%=basePath%>book/dishes/backstageversion/list!importExcel" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px"/><br/><br/>  
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<input type="hidden" id="importCompanyId" name="importCompanyId" value=""/>
<input type="hidden" id="importStallId" name="importStallId" value=""/>
<a href="<%=basePath%>book/dishes/backstageversion/list!exportOrder">下载模板</a>
</form>
</div>
<input id="btnImport" class="btn btn-default" type="button" value="导入"/></li>

下面是js

    <!-- Bootstrap -->
<link href="<%=path %>/res/admin/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="<%=path %>/res/admin/css/xy_css.css" rel="stylesheet" type="text/css">
<link href="<%=path %>/res/admin/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script src="<%=path %>/res/admin/js/jquery.min.js"></script>
<script src="<%=path %>/res/admin/js/bootstrap.min.js"></script>
<link href="<%=path %>/res/admin/jquery-select2/3.4/select2.css" rel="stylesheet" type="text/css" />
<script src="<%=path %>/res/admin/jquery-select2/3.4/select2.min.js"></script>
<script src="<%=path %>/res/admin/jquery-select2/3.4/select2_locale_zh-CN.js"></script> <script type="text/javascript" src="<%=basePath%>res/admin/js/layer/layer.js"></script>
<script type="text/javascript">
$(document).ready(function (){//加载页面时执行select2
$("select").select2();
//弹出导出窗口
$("#btnImport").click(function(){
var importStallId = $("#stallId option:selected").val();
var importCompanyId = $("#companyId option:selected").val();
$("#importCompanyId").val(importCompanyId);
$("#importStallId").val(importStallId);
if(importStallId==null || importStallId==""){
alert("请选择档口");
}else{
layer.open({
type: 1,
skin: 'layui-layer-rim', //加上边框
area: ['600px', '350px'], //宽高
content: $('#importBox')
});
}
});
});

3下面是后台代码Action 类

一:下载模板代码

    /**
* 下载模板
* @throws IOException
*/
public void exportOrder() throws IOException{
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
File file = null;
InputStream inputStream = null;
ServletOutputStream out = null;
try {
request.setCharacterEncoding("UTF-8");
String realPath = ServletActionContext.getServletContext().getRealPath("/");
file = new File(realPath+"WEB-INF/mailtemplate/dishes.xlsx");
inputStream = new FileInputStream(file);
response.setCharacterEncoding("utf-8");
response.setContentType("application/msexcel");
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode("菜品导入" + ".xlsx", "UTF-8"));
out = response.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Excel文件的内容输出到浏览器中
while ((bytesToRead = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null)
inputStream.close();
if (out != null)
out.close();
if (file != null)
file.delete(); // 删除临时文件
}
}

二: 导入代码

    /**
* 导入
* @throws IOException
*/
public void importExcel() throws IOException {
List<Dishes> dishesList = getDishesList(file);
if(dishesList !=null && dishesList.size()>0){
for(Dishes dishes : dishesList){
targetService.add(dishes);
}
}
String basePath = ServletActionContext.getServletContext().getContextPath();
ServletActionContext.getResponse().sendRedirect(basePath + "/book/dishes/backstageversion/list");
}
/**
* 读取Excel数据
* @param filePath
* @return List
* @throws IOException
*/
private List<Dishes> getDishesList(String filePath) throws IOException {
XSSFWorkbook workBook= null;
InputStream is = new FileInputStream(filePath);
try {
workBook = new XSSFWorkbook(is);
} catch (Exception e) {
e.printStackTrace();
}
Dishes dishes=null;
List<Dishes> dishesList = new ArrayList<Dishes>();
//循环工作表sheet
//List<XSSFPictureData> picturesList = getPicturesList(workBook);//获取所有图片
for(int numShett = 0;numShett<workBook.getNumberOfSheets();numShett++){
XSSFSheet sheet = workBook.getSheetAt(numShett);

//调用获取图片
             Map<String, PictureData> pictureDataMap = getPictureDataMap(sheet, workBook);

if(sheet==null){
continue;
}
//循环Row
for(int rowNum=1;rowNum<=sheet.getLastRowNum();rowNum++){
Row row = sheet.getRow(rowNum);
if(row==null){
continue;
} dishes = new Dishes();
//Cell
Cell dishesName = row.getCell(0);
if(dishesName==null){
continue;
}
dishes.setName(getValue(dishesName));//菜品名称
Cell price = row.getCell(1);
if(price==null){
continue;
}
dishes.setPrice(Double.parseDouble(getValue(price)));//优惠价格
Cell oldPrice = row.getCell(2);
if(oldPrice==null){
continue;
}
dishes.setOldPrice(Double.parseDouble(getValue(oldPrice)));//原价格
Cell summary = row.getCell(3);
if(summary==null){
continue;
}
dishes.setSummary(getValue(summary));//菜品描述
Cell online = row.getCell(4);
if(online==null){
continue;
}
dishes.setOnline(Integer.parseInt(getValue(online)));//是否上下架
Cell packCharge = row.getCell(5);
if(packCharge==null){
continue;
}
dishes.setPackCharge(Double.parseDouble(getValue(packCharge)));//打包费
Cell stockNumber = row.getCell(6);
if(stockNumber==null){//库存为必填
continue;
}
dishes.setStockNumber(Integer.parseInt(getValue(stockNumber)));//每餐库存
Cell immediateStock = row.getCell(7);
if(immediateStock==null){//当前库存
continue;
}
dishes.setImmediateStock(Integer.parseInt(getValue(immediateStock)));//当前库存
Cell purchaseLimit = row.getCell(8);
if(purchaseLimit==null){
continue;
}
dishes.setPurchaseLimit(Integer.parseInt(getValue(purchaseLimit)));//限购数量
Cell restrictionType = row.getCell(9); if(restrictionType==null){
continue;
}
dishes.setRestrictionType(Integer.parseInt(getValue(restrictionType)));//限购方式
Cell sort = row.getCell(10);
if(sort==null){
continue;
}
dishes.setSort(Integer.parseInt(getValue(sort)));//排序
Cell contents = row.getCell(11);
if(contents==null){
continue;
}
dishes.setContents(getValue(contents));//菜品详情
dishes.setCreateTime(new Date());
Company company = companyService.load(importCompanyId);
Stall stall = stallService.load(importStallId);
dishes.setCompany(company);
dishes.setStall(stall);

//set 图片
                 PictureData pictureData = pictureDataMap.get(rowNum+"");
                 if(pictureData !=null){
                  String upImageUrl = UpImage(pictureData.getData());
                  dishes.setImage(upImageUrl);
                 }

                dishesList.add(dishes);
}
}
return dishesList;
}
/**
* 得到Excel表中的值
* @param hssfCell
* @return String
*/
@SuppressWarnings("unused")
private String getValue(Cell cell){
DecimalFormat df = new DecimalFormat("###################.###########");
if(cell.getCellType()==cell.CELL_TYPE_BOOLEAN){
return String.valueOf(cell.getBooleanCellValue());
}
if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
return String.valueOf(df.format(cell.getNumericCellValue()));
}else{
return String.valueOf(cell.getStringCellValue());
}
}

4: get set 方法

    private String file;

    private Long importCompanyId;
private Long importStallId;
    public String getFile() {
return file;
} public void setFile(String file) {
this.file = file;
} public Long getImportCompanyId() {
return importCompanyId;
} public void setImportCompanyId(Long importCompanyId) {
this.importCompanyId = importCompanyId;
} public Long getImportStallId() {
return importStallId;
} public void setImportStallId(Long importStallId) {
this.importStallId = importStallId;
}

公司需求改变要增加导入图片到又拍云服务器,所以下面增加读取excel图片

    /**
* 读取Excel 中图片
* @param sheet
* @param workBook
* @return
*/
private Map<String, PictureData> getPictureDataMap(XSSFSheet sheet,XSSFWorkbook workBook){
Map<String, PictureData> map = new HashMap<String,PictureData>();
for(POIXMLDocumentPart dr : sheet.getRelations()){
if(dr instanceof XSSFDrawing){
XSSFDrawing drawing = (XSSFDrawing) dr;
List<XSSFShape> shapesList = drawing.getShapes();
if(shapesList !=null && shapesList.size()>0){
for(XSSFShape shape : shapesList){
XSSFPicture pic = (XSSFPicture) shape;
XSSFClientAnchor anchor = pic.getPreferredSize();
CTMarker cTMarker = anchor.getFrom();
String picIndex = cTMarker.getRow()+"";
map.put(picIndex, pic.getPictureData());
}
}
}
}
return map;
}
    /**
* 上传图片到又拍云
* @param bytes
* @return
*/
private String UpImage(byte[] bytes){
String fileName = UUID.randomUUID().toString() + ".jpg";
String uploadURL = UpYunClient.upload(fileName, bytes);
return uploadURL;
}

注意:请用Poi  jar 3.9 版本 不然读取图片代码会报错

java 使用poi 导入Excel 数据到数据库的更多相关文章

  1. 【转】 如何导入excel数据到数据库,并解决导入时间格式问题

    在办公环境下,经常会用到处理excel数据,如果用写程序导入excel数据到数据库那就太麻烦了,涉及解析excel,还要各种格式问题,下面简单利用数据库本身支持的功能解决这类导入问题. 准备 创建表 ...

  2. Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)

    ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...

  3. JAVA通过poi对Excel数据在(jsp+ssh)环境下导入导出

    POI的下载与安装  请到网站http://www.apache.org/dyn/closer.cgi/poi/右击超链接2.5.1.zip下载压缩包poi-bin-2.5.1-final-20040 ...

  4. .net导入excel数据到数据库中

    在开发过程中我们经常面临着需要将数据导出或者导入到系统中,例如一些生产管理系统,项目管理系统等等都会有这样的需求: 将excel数据到系统中思路:获取excel中每一行的数据,然后存入集合中,批量添加 ...

  5. [Java] 高效快速导入EXCEL数据

    需求1.高效率的以excel表格的方式导入多条数据.2.以身份证号为唯一标识,如果身份证号已存在,则该条数据不导入. 分析刚开始的时候是传统的做法,解析excel数据,获取单个对象,判断身份证是否已存 ...

  6. POI 导入excel数据自动封装成model对象--代码

    所有的代码如下: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; ...

  7. 导入excel数据到数据库

    1.上传excel到服务器 jsp页面代码 <form action="actionname" method="post" id="form1& ...

  8. Java使用POI导入Excel异常Cannot get a text value from a numeric cell 解决

    异常原因:Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串并写入数据库时,就会出现Cannot get a text value from a numeric c ...

  9. PHP 导入Excel数据 到数据库

    /** * 导入excel * @throws \PHPExcel_Exception * @throws \PHPExcel_Reader_Exception */ public function ...

随机推荐

  1. JVM 引用类型

    1.强引用 强引用,是在我们的开发工作当中普遍存在的.如果一个对象具有强引用,那就类似我们经常穿的衣服啊等必不可少的生活用品,我们肯定不会把他扔掉,同样jvm的垃圾回收器也不会回收它.当内存空间不足的 ...

  2. CentOS7更换阿里yum源

    更换之前确保自己安装wget yum list wget 若没有安装: yum -y install wget 首先备份原版/etc/yum.repos.d/CentOS-Base.repo cd / ...

  3. 转:为什么说Java中只有值传递

    原文:https://www.cnblogs.com/wchxj/p/8729503.html 错误理解 在开始深入讲解之前,有必要纠正一下大家以前的那些错误看法了.如果你有以下想法,那么你有必要好好 ...

  4. 最小树形图模板 UVA11183

    题意:给定n个节点m条边的有向带权图,求以0为根节点的最小树形图权值大小 用这个代码的时候要注意,这里的数据是从0开始的,边也是从0开始算, 所以在打主代码的时候,如果是从1开始,那么算法里面的从0开 ...

  5. 教你如何用python和pygame制作一个简单的贪食蛇游戏,可自定义

    1.效果图 2.完整的代码 #第1步:导出模块 import pygame, sys, random from pygame.locals import * # 第2步:定义颜色变量,在pygame中 ...

  6. opencv安装中的各种问题汇总

    问题1:opencv-2.4.10/modules/gpu/src/nvidia/core/NCV.cu(356): error : namespace "std" has no ...

  7. 前端——语言——Core JS——《The good part》读书笔记——第四章节(Function)

    本章介绍Function对象,它是JS语言最复杂的内容. Java语言中没有Function对象,而是普通的方法,它的概念也比较简单,包含方法的重载,重写,方法签名,形参,实参等. JS语言中的Fun ...

  8. nginx配置访问密码,输入用户名和密码才能访问

    1. 安装 htpasswd 工具 yum install httpd-tools -y 设置用户名和密码,并把用户名.密码保存到指定文件中: [sandu@bogon conf]$ sudo mkd ...

  9. SVN代码迁移到GITlab

    ==================================================================================================== ...

  10. 2020 安恒2月月赛 misc

    题目链接:https://pan.baidu.com/s/19l54Nukt6evOr4UgbHMXIQ 提取码:1qbs 0x01 lemonEssence 咦?在kali打开是出错,改宽后图片变了 ...