java 使用poi 导入Excel数据到数据库的步骤
作者:阿若蜜意 发布时间:2024-01-19 11:21:34
标签: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" rel="external nofollow" rel="external nofollow" >下载模板</a>
</form>
</div>
<!-- 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" rel="external nofollow" rel="external nofollow" >下载模板</a>
</form>
</div>
下面是js
<!-- Bootstrap -->
<link href="<%=path %>/res/admin/css/bootstrap.min.css" rel="external nofollow" rel="stylesheet" type="text/css" />
<link href="<%=path %>/res/admin/css/xy_css.css" rel="external nofollow" rel="stylesheet" type="text/css">
<link href="<%=path %>/res/admin/css/font-awesome.min.css" rel="external nofollow" 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="external nofollow" 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 版本 不然读取图片代码会报错
来源:https://www.cnblogs.com/SHMILYHP/p/8327861.html


猜你喜欢
- 把程序放到一个文件中,然后包含再call就可以了。(JMAIL4.3)<%'警告函数sub w_msg(messag
- 是时候稍微总结一下前一段时间的PHP简单系统制作技巧了。 前一段时间主要讲述了如何用PHP读取与查询MySQL中的数据,并向大家着重解释了如
- 报错信息最近闲来无事,用python的tkinter库开发了一款带日程提醒的万年历桌面程序。在程序开发结束开始打包时,却发现一直报错PyIn
- 本文实例为大家分享了python感知机实现的具体代码,供大家参考,具体内容如下一、实现例子李航《统计学方法》p29 例2.1正例:x1=(3
- 我想做一个页面,10秒后转向其它页。想在网页中显示10秒的倒计时。谢谢了。对JS不懂 方法一:<html><h
- 当页面中引用template.js文件之后,脚本将创建一个TrimPath对象供你使用。 parseDO
- MySQL 修改密码实例详解许久不用MySQL了,今天打开HediSQL连接mysql时发现root密码忘记了,修改密码操作捣鼓了一阵子,记
- 1.编写python flask代码,简单写一个加法的接口,命名为sum.pyimport jsonfrom flask import Fl
- python的其中一个强大之处就是它可以方便的集成很多的非标准库,今天在GitHub上溜达又发现了一个脏话处理神器,导入better_pro
- 本文介绍Golang pipe,以及在不同场景下的应用。Pipe介绍pipe实现从一个进程重定向至另一个进程,它是双向数据通道,用于实现进行
- Linux安装MySQL笔记1、在安装MySQL数据库服务器前,确保你的linux系统是可以连接网络的,下面我们将通过源码方式来安装mysq
- 迄今为止,导出/导入工具集仍是跨多个平台转移数据所需劳动强度最小的首选实用工具,尽管人们常常抱怨它速度太慢。导入只是将每条记录从导出转储文件
- 一、下载instant client1.附链接:http://www.oracle.com/technetwork/topics/winx6
- 一行命令搭建一个基于python的http文件传输服务由于今天朋友想要一个文件,而我恰好有,因为这个文件比较大,网速不是很给力,所以想到了p
- 今天看YUI的视频教程,YUI的工程师介绍的一款在线的图片压缩工具,也许你用过,也许没有,不过我这里强烈推荐大家用一下,我用smush.it
- python中的多线程是一个非常重要的知识点,今天为大家对多线程进行详细的说明,代码中的注释有多线程的知识点还有测试用的实例。import
- 本文讲述一个用Python写的小程序,用于有注入点的链接,以检测当前数据库用户是否为sa,详细代码如下:# Code by zhaoxiao
- xhEditor简介xhEditor是一个基于jQuery开发的简单迷你并且高效的可视化HTML编辑器,基于网络访问并且兼容IE 6.0+,
- 1 基本概念1.1 命名空间 (namespace)命名空间是变量名到对象的映射(name -> obj)。目前大多数的命名空间以类似
- 本文实例为大家分享了vue实现表单录入的具体代码,供大家参考,具体内容如下最终效果:代码:<template> <div