这个工具类可以解决 是2003还是2007版的
工具方法不是自己写的 自己稍微的改造了下 变成了工具类.
对数值类型会变成dubbo类型的做了调整,前面是几位小数,导入到数据库还是几位,整数不会变成0.0类型的,没有判断日期类型 如果需要可自行去修改下
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
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;
/**
*
* @ClassName: ImportExecl
* @Description: Excel导入
* @author wangkaike
* @date 2017年5月16日 下午1:00:24
*
*/
public class ImportExecl {
/** 总行数 */
private int totalRows = 0;
/** 总列数 */
private int totalCells = 0;
/** 错误信息 */
private String errorInfo;
/** 构造方法 */
public ImportExecl() {
}
public int getTotalRows() {
return totalRows;
}
public int getTotalCells() {
return totalCells;
}
public String getErrorInfo() {
return errorInfo;
}
public boolean validateExcel(String filePath) {
/** 检查文件名是否为空或者是否是Excel格式的文件 */
if (filePath == null || !(isExcel2003(filePath) ||isExcel2007(filePath))) {
errorInfo = "文件名不是excel格式";
return false;
}
/** 检查文件是否存在 */
File file = new File(filePath);
if (file == null || !file.exists()) {
errorInfo = "文件不存在";
return false;
}
return true;
}
public List<Map<String,Object>> read(String filePath) {
List<Map<String,Object>> dataLst = new ArrayList<Map<String,Object>>();
InputStream is = null;
try {
/** 验证文件是否合法 */
if (!validateExcel(filePath)) {
System.out.println(errorInfo);
return null;
}
/** 判断文件的类型,是2003还是2007 */
boolean isExcel2003 = true;
if (isExcel2007(filePath)) {
isExcel2003 = false;
}
/** 调用本类提供的根据流读取的方法 */
File file = new File(filePath);
is = new FileInputStream(file);
dataLst = read(is, isExcel2003);
is.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
/** 返回最后读取的结果 */
return dataLst;
}
/**
* @描述:根据流读取Excel文件
* @参数:@param inputStream
* @参数:@param isExcel2003
* @参数:@return
* @返回值:List
*/
public List<Map<String,Object>> read(InputStream inputStream, boolean isExcel2003) {
List<Map<String,Object>> dataLst = null;
try {
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
if (isExcel2003) {
wb = new HSSFWorkbook(inputStream);
} else {
wb = new XSSFWorkbook(inputStream);
}
dataLst = read(wb);
} catch (IOException e) {
e.printStackTrace();
}
return dataLst;
}
/**
*
* @描述:读取数据
* @参数:@param Workbook
* @参数:@return
* @返回值:List<List<String>>
*/
private List<Map<String,Object>> read(Workbook wb) {
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//List<List<String>> dataLst = new ArrayList<List<String>>();
/** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
this.totalRows = sheet.getPhysicalNumberOfRows();
int rowNum = sheet.getLastRowNum();
/** 得到Excel的列数 */
if (this.totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
/** 循环Excel的行 */
for (int r = 1; r <= rowNum; r++) {
Row row = sheet.getRow(r);
Map<String,Object> dataMap = new HashMap<String,Object>();
if (row == null) {
continue;
}
/** 循环Excel的列 */
for (int c = 0; c < this.getTotalCells(); c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
//cellValue = +"";
Long longValue = Math.round(cell.getNumericCellValue());
Double doubleVal = cell.getNumericCellValue();
if(Double.parseDouble(longValue + ".0") == doubleVal){ //判断是否含有小数位.0
cellValue = longValue+"";
}else{
cellValue=doubleVal+"";
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
cellValue = "";
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
dataMap.put("celName"+c,cellValue);
}
}
list.add(dataMap);
}
return list;
}
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* @描述:是否是2007的excel,返回true是2007
* @参数:@param filePath 文件完整路径
* @参数:@return
* @返回值:boolean
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
==================运用===================
html部分( purExcelParse.js代码稍后贴上)
<script type="text/javascript"src="static/js/jquery.form.js">
</script>
<script
type="text/javascript" src="static/js/purExcelParse.js">
</script>
<a id="batchImportBtn">导入Excel</a>
<div class="order_pop w470 mt100" id="importModel" style="display: none;position:fixed;left:50%;top:50%;width:300px;
height:150px;margin-left:-150px;margin-top:-150px;background:#F0FFF0;">
<h2 class="order_pop_tit">
<span class="fl">本地导入</span>
<a href="javascript:void(0)" id="importCrossBtn"></a>
</h2>
<div class="order_popcon mb20">
<p class="julko">第一步:<a href="static/template/muban.xls" title="" target="_self" class="ablue">下载模板</a><span class="ml5"></span></p>
<p class="julko">第二步:<a id="uploadLink" href="javascript:void(0)" title="" target="_self" class="ablue">上传文件</a><span id="path" class="ddpmo ml15"></span></p>
<p class="pb22 pt27 textR">
<a id="importOkBtn" href="javascript:void(0)" class="confirmBtn w80Btn mr10">确 定</a>
<a id="imporCancleBtn" href="javascript:void(0)" class="cancelBtn2 w80Btn">取 消</a>
</p>
</div>
<div style="display: none">
<form id="uploadExcellForm" action="supply/batchImport" method="post" enctype="multipart/form-data">
<input type="file" id="uploadFile" name="uploadFile" onchange="$('#path').html(this.value)">
<input type="submit" id="ok" value="提 交">
</form>
</div>
</div>
purExcelParse.js
$(document).ready(
function() {
// 1、 本地批量导入
rowNum = 0;
$(function() {
var options = {
beforeSubmit : function() {
$("#importModel")[0].style.display = 'none';
$("#mask")[0].style.display = 'none';
var FileName = new String($("#uploadFile").val());// 文件名
var extension = new String(FileName.substring(FileName
.lastIndexOf(".") + 1, FileName.length));// 文件扩展名
if (extension != "xls")// 你可以添加扩展名
{
alert("." + extension + "不是excel文件,请下载模板");
return false;
}
},
success : function(result) {
if (result.code == 200) {
alert("导入成功");
} else {
alert(result.msg);
return false;
}
}
};
$('#uploadExcellForm').ajaxForm(options);
});
// 2、'本地批量导入'弹框
$("#batchImportBtn").click(function() {
var hiddenTxt = $("#hiddenTxt").val();
$("#importModel")[0].style.display = 'block';
$("#mask")[0].style.display = 'block';
});
// 3.本地批量导入'确认
$("#importOkBtn").click(function() {
if ($("#path").html() == "") {
$("#importModel")[0].style.display = 'none';
$("#mask")[0].style.display = 'none';
} else {
$("#ok").click();
}
});
// 4.本地批量导入'取消'
$("#imporCancleBtn").click(function() {
$("#importModel")[0].style.display = 'none';
$("#mask")[0].style.display = 'none';
});
// 4.本地批量导入'关闭'
$("#importCrossBtn").click(function() {
$("#importModel")[0].style.display = 'none';
$("#mask")[0].style.display = 'none';
});
// 4.本地批量导入,第二步骤'上传文件'
$("#uploadLink").click(function() {
$("#uploadFile").click();
});
});
后台代码:
@RequestMapping(value = "/batchImport")
@ResponseBody
public RespData batchImportProducts(@RequestParam("uploadFile") MultipartFile uploadFile) throws Exception{
InputStream file = uploadFile.getInputStream();
String originalFilename = uploadFile.getOriginalFilename();
/** 判断文件的类型,是2003还是2007 */
boolean isExcel2003 = true;
if (ImportExeclUtils.isExcel2007(originalFilename)) {
isExcel2003 = false;
}
RespData rd= iProSupplyExcelUploadService.saveProProductSearchSort(file,isExcel2003);
String jsonString = JSON.toJSONString(rd);
System.err.println(jsonString);
return rd;
}
@Override
public RespData saveProProductSearchSort(InputStream file, boolean isExcel2003) {
ImportExeclUtils poi = new ImportExeclUtils ();
List<Map<String,Object>> read = poi.read(file, isExcel2003);
for (Map<String, Object> map : read) {
String keyWord = (String) map.get("celName0");
String categoryCode = (String) map.get("celName1");
String productId = (String) map.get("celName2");
String sort = (String) map.get("celName3");
System.err.println("keyWord"+keyWord+" categoryCode"+categoryCode+" productId"+productId+" sort"+sort);
}
return null;
}
如果有为空的 也不报错,若为必填项 则需要判断
上面的 弹框比较丑陋 引用 layer 插件
效果图
PS 不知道为什么 自己写在 弹出层上的点击事件不好用,只能修改了之前的js方法,不知道是能不能在弹出层上定义方法 ,有知道的可以说下
—- PS 今天在做另外一个例子,明白了 为什么点击事件不好使了 ,我把事件放在弹框前,放后面就可以了
官网下载 —- 此处引进的自己项目静态工程服务里面的(貌似只需要引入js 我css也引了)
—JQuery 必须在1.8 以上
<!-- 弹框 -->
<script src="<%=jsPath %>static/plugins/layer/layer.js" type="text/javascript"></script>
<link href="<%=jsPath %>static/plugins/layui/css/layui.css" rel="stylesheet" type="text/css" />
$(document).ready(
function() {
$("#batchImportBtn").click(function() {
var html ="<div id='importModel'>";
html+="<h2 >";
html+=" <a href='javascript:void(0)' id='importCrossBtn'></a></h2>";
html+="<div>";
html+="<p >第一步:<a href='static/template/muban.xls' title='' target='_self' class='ablue'>下载模板</a><span class='ml5'></span></p>";
html+="<form id='uploadExcellForm' enctype='multipart/form-data'>";
html+="<p >第二步:<input type='file' id='uploadFile' name='uploadFile' onchange='$('#path').html(this.value)' ><span id='path' ></span>";
html+="</form>"
html+="</div>";
html+="</div>";
//弹框
layer.open({
type: 1,
title:'导入Excel',
area: ['300px', '260px'],
shadeClose: true, //点击遮罩关闭
content: html,
btn: ['确认', '取消'],
btnAlign: 'c',
yes: function(index, layero){
var FileName = new String($("#uploadFile").val());// 文件名
var extension = new String(FileName.substring(FileName.lastIndexOf(".") + 1, FileName.length));// 文件扩展名
if (extension != "xls"){
alert("." + extension + "不是excel文件,请下载模板");
return false;
}
$.ajax({
url:'proSupplySearch/batchImport',
type: 'post',
dataType: 'json',
processData:false,
contentType:false,
data:new FormData($('#uploadExcellForm')[0]),
success: function (data) {
if (data.code=200) {
alert(data.msg);
layer.closeAll('page');
// window.location.reload();
} else {
alert(data.msg);
layer.closeAll('page');
// location.reload();
return false;
}
}
});
},
end: function () {
//不管操不操作,重新刷新页面,如果不喜欢,可以放在回调里面
location.reload();
}
});
});
});
后台代码不变 可以继续使用
欢迎相互交流,有什么问题可以留言,对我留下的问题,大家也可以说