java 使用poi 导入Excel 数据到数据库
由于我个人电脑装的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 数据到数据库的更多相关文章
- 【转】 如何导入excel数据到数据库,并解决导入时间格式问题
在办公环境下,经常会用到处理excel数据,如果用写程序导入excel数据到数据库那就太麻烦了,涉及解析excel,还要各种格式问题,下面简单利用数据库本身支持的功能解决这类导入问题. 准备 创建表 ...
- Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)
ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...
- 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 ...
- .net导入excel数据到数据库中
在开发过程中我们经常面临着需要将数据导出或者导入到系统中,例如一些生产管理系统,项目管理系统等等都会有这样的需求: 将excel数据到系统中思路:获取excel中每一行的数据,然后存入集合中,批量添加 ...
- [Java] 高效快速导入EXCEL数据
需求1.高效率的以excel表格的方式导入多条数据.2.以身份证号为唯一标识,如果身份证号已存在,则该条数据不导入. 分析刚开始的时候是传统的做法,解析excel数据,获取单个对象,判断身份证是否已存 ...
- POI 导入excel数据自动封装成model对象--代码
所有的代码如下: import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; ...
- 导入excel数据到数据库
1.上传excel到服务器 jsp页面代码 <form action="actionname" method="post" id="form1& ...
- Java使用POI导入Excel异常Cannot get a text value from a numeric cell 解决
异常原因:Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串并写入数据库时,就会出现Cannot get a text value from a numeric c ...
- PHP 导入Excel数据 到数据库
/** * 导入excel * @throws \PHPExcel_Exception * @throws \PHPExcel_Reader_Exception */ public function ...
随机推荐
- 已解决:解压Python-3.6.1.tar.xz提示tar (child): xz:无法 exec: 没有那个文件或目录
安装一个xz后解决了 yum install xz 再次解压成功了
- VS2015打开失败
在使用VS2015过程中之前能打开的.Net项目,结果突然就不能使用了.我就不能理解了,后来找了一个方法,抱着试试的心态结果就成功了. 解决办法 第一步: 开始-->所有程序-->Micr ...
- 转:为什么说Java中只有值传递
原文:https://www.cnblogs.com/wchxj/p/8729503.html 错误理解 在开始深入讲解之前,有必要纠正一下大家以前的那些错误看法了.如果你有以下想法,那么你有必要好好 ...
- AcWing 853. 有边数限制的最短路 bellman-ford 结构体
//存在负权值 处理负环 //如果能求出来 一般是不存在负权回路 //如果有负回路 那最小距离可能是负无穷 #include <cstring> #include <iostream ...
- mybatis--Spring整合mybatis
今天学习了mybatis整合Spring开发,做了一个mybatis+spring的小实例 (1)首先,创建数据库my,并在数据库my中创建表user create database my; use ...
- pip install 安装指定版本的包
pip install 安装指定版本的包 要用 pip 安装指定版本的 Python 包,只需通过 == 操作符 指定 pip install robotframework==2.8.7 将安装r ...
- linux 磁盘100% 清理
df -h 查看磁盘使用有一个vdb满了 df -i 查看inode 使用率 显示文件大小: du -sh /* du参数: -a : 列出所有的文件与目录容量,因为默认仅统计目录下面的文件量而 ...
- git密码相关问题
一.解决:每次都需要输入账号密码 git config --global credential.helper store 二.后期git密码更改后,重置密码操作 git config --system ...
- 记录STM32调试
问题:加入红外初始化后,程序卡在红外初始化处 解决思路: 1.确认时钟是不是好的 2.把定时器分解调试(输入捕获.溢出分开一步一步弄) 已解决:定时器的溢出中断 注意:STM32Cube配置好后,需要 ...
- selenium配合phantomjs实现爬虫功能,并把抓取的数据写入excel
# -*- coding: UTF-8 -*- ''' Created on 2016年5月13日 @author: csxie ''' import datetime from Base impor ...