前台采用freemarker,后台Java,利用poi插件完成的Excel上传,解析,到存储到数据库。
<#include "/commons/banner.ftl" encoding="UTF-8">
<style type='text/css'>
.labelx
{
height: 30px;
vertical-align: moddle;
padding: 6px 0px 0px 0px;
color:#006699;
}
.labely
{
height: 30px;
text-align: right;
vertical-align: moddle;
padding: 6px 0px 0px 0px;
color:#006699;
}
</style>
<#--合同编号-->
<#assign contractNos = "">
<#if contractnoCommands?size!=0>
<#list contractnoCommands as contractnoCommand>
<#list contractnoCommand ? keys as key>
<#assign contractNos = contractNos + '|' +contractnoCommand[key] >
</#list>
</#list>
</#if>
<#if contractNos?exists && contractNos?length gt 0>
<#assign contractNos = '^(' + contractNos?substring(1) + ')$'>
</#if>
<table width="100%" cellpadding=0 border="0" cellspacing=0 class="outline">
<tr>
<td>
<div class="tabTit_wrap">
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><h3> ${moduleName}</h3></td>
<td align='right'>
<input type='button' class='button7' href='?action=download' method='link' value='下载模板' />
<input type='button' class='button7' value='导入帮助' οnclick="Proxy.openwin('/interface/supplyinfo/importhelp.html')"/>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr height="100%">
<td class="workspaces">
<div class="workspace" id='workspace'>
<table border="0" cellpadding="0" cellspacing="0" align="center" class="modify" >
<tr class='normal'>
<td class='labelx' colspan="4" style="text-align: left;">流程:<span style="font-weight: bold;">下载模板</span> - 填写数据 - 上传 - 确认导入</td>
</tr>
<tr class='normal'>
<td class='labelx' colspan="4" style="text-align: left; padding-left: 40px">说明:下载模板后,请不要修改模板格式。一次最多导入100条。上传后会显示数据,可以通过“选择”或“全选”要上传的数据。确认无误后请点击“确认导入”。</td>
</tr>
<#if textmessage??>
<tr><td class='labelx' colspan="4" style="text-align: left; padding-left: 40px;color: red;">${textmessage!''}</td></tr>
</#if>
<tr>
<td class="e_tit" colspan="4" align="left">o 上传文件</td>
</tr>
<form name="valueform" id='valueform' action="?action=upload" enctype="multipart/form-data" method="POST" οnsubmit="return uploadform(this);" >
<tr class='normal'>
<td class='labely'>上传文件:</td>
<td class='context' colspan='3'>
<input type="file" name="uploadfile" class="text">
<input type="submit" value="上传" class="btnstyle"/>
</td>
</tr>
</form>
<tr>
<td class="e_tit" colspan="4" align="left">o 材料供应信息导入</td>
</tr>
</table>
<form name="save_${keyword}" id='save_${keyword}' action="?action=importExcel" method="POST" οnsubmit="return pullback(this);" validate='true' target='save'>
<table border="0" cellpadding="0" cellspacing="0" align="center" class="desking" >
<tr node="aa" >
<td colspan='4' style="overflow: auto;" valign="top">
<table border="0" cellpadding="0" cellspacing="0" align="center" style="width:98%;height:100%;" class="tab_list" style="border-left: 1px solid #D9D9D9;border-right: 1px solid #D9D9D9;">
<tr class='row1'>
<#--全选操作-->
<td class='cell1' width="5%" >
<input type='checkbox' id='select' name="select" οnclick="checkall();"/>
</td>
<#-- 序号 -->
<td class='cell1' width='5%' >序号</td>
<#-- 列表标签 -->
<td class='cell1' width='10%' >合同编号</td>
<td class='cell1' width='10%' >产品类型</td>
<td class='cell1' width='10%' >产品名称</td>
<td class='cell1' width='10%' >其它产品名称</td>
<td class='cell1' width='8%' >品种牌号</td>
<td class='cell1' width='8%' >规格型号</td>
<td class='cell1' width='8%' >生产批次</td>
<td class='cell1' width='10%' >材料发货时间</td>
<td class='cell1' width='8%' >供应数量</td>
<td class='cell1' width='8%' >计量单位</td>
</tr>
<#if !rowList?exists || rowList?size==0>
<tr class='row7' >
<td colspan="12" class='cell3' align='center'> 数据为空</td>
</tr>
<#else>
<#--隐藏域 获取表头titleMaps-->
<input type="hidden" id="titleMaps" name="titleMaps" value="${titleMaps}"/>
<#list rowList as command>
<tr class='row7' light='true'>
<td class='cell3' align="center">
<input type="checkbox" name="sca" value="${command_index}" οnclick="checkone(this)"/>
</td>
<td class='cell3' align="center">${command_index+1}</td>
<#list rowList[command_index] as cell>
<#--<#if cell_index == titleMap["其它产品名称"] >
<input type="hidden" size='15' class="tdinput" name="${command_index}_${cell_index}" value="${cell}" />
<#else>-->
<td class='cell3' >
<span>${cell}</span>
<input type="hidden" size='15' class="tdinput" name="${command_index}_${cell_index}" value="${cell}" readonly />
</td>
</#list>
</tr>
</tr>
</#list>
</#if>
</table>
</td>
</tr>
</table>
<input type="hidden" id='operate_op' name='operate_op' require='false' value="${Session.auth.id!''}" />
<input type="hidden" id='operate_name' name='operate_name' require='false' value="${Session.auth.accounts!''}" />
<input type="hidden" id='operate_date' name='operate_date' require='false' value="${Sysdate!''}" />
</div>
</td>
</tr>
<tr>
<td height="30px" align="right" valign="bottom" >
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="100%" height="35" align="right" class="tabTit_bottom" >
<#if rowList?exists && rowList?size!=0>
<input type='submit' class='button7' value='确认导入' />
</#if>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
<div id="lock"></div>
<div id="loading"></div>
<#include "/commons/bottom.ftl" encoding="UTF-8">
<script language="JavaScript" type="text/javascript" >
enter('modify');
<#--全选事件-->
function checkall()
{
var allcheckBoxs = document.getElementsByName("sca") ;
if(!document.getElementById("select").checked ){
for(var i=0;i<allcheckBoxs.length;i++){
allcheckBoxs[i].checked = false;
}
return ;
}
<#--全选过慢 提示等待-->
document.getElementById("loading").innerHTML = "<img src='/themes/skyblue/images/loading.gif' alt=''> 全选中.....";
document.getElementById("lock").style.display = "block";
document.getElementById("loading").style.display = "block"
<#--执行全选-->
window.setTimeout(checkallt,500);
}
<#--全选事件 -->
function checkallt()
{
<#--获得多选框总数 作为总行数-->
var rowsum = document.getElementsByName("sca");
if(rowsum ==null)
{
<#--全选结束 隐藏等待-->
document.getElementById("lock").style.display = "none";
document.getElementById("loading").style.display = "none";
return;
}
<#--保存有错误的行-->
var errorrow = "";
if(rowsum!= null && rowsum.length != 0)
{
nextrow:for(row = 0; row < rowsum.length; row++)
{
for(cell = 0; cell < Number(${CELLSUM!'0'}) - 1; cell++)
{
<#--行+列是input的name-->
var name = row + "_" + cell;
var color = document.getElementsByName(name)[0].style.color;
<#--如果有错误 跳出 此行-->
if(color == "red")
{
errorrow += "," + (row+1);
continue nextrow;
}
}
<#--如果没有跳出 就选中-->
rowsum[row].checked = true;
}
}
<#--全选结束 隐藏等待-->
document.getElementById("lock").style.display = "none";
document.getElementById("loading").style.display = "none";
if("" != errorrow){
$("#select").attr("checked",false);
alert("第" + errorrow.replace(",","") + "行存在错误数据或必填项未填写,没有选中;\n未选中的行请更改数据后再导入!");
}
}
<#--上传文件表单提交-->
function uploadform(_this)
{
if(_this.uploadfile.value == "")
{
alert("请先选择上传文件");
return false;
}
//获取文件后缀名
var value = _this.uploadfile.value.split(".")[_this.uploadfile.value.split(".").length -1];
if(value != "xls" && value != "xlsx")
{
alert("文件格式错误");
return false;
}
document.getElementById("loading").innerHTML = "<img src='/themes/skyblue/images/loading.gif' alt=''> 导入中....."
document.getElementById("lock").style.display = "block";
document.getElementById("loading").style.display = "block";
return true;
}
<#--选中事件-->
function checkone(_this)
{
<#--如果选中要取消 不做判断-->
if(!(_this.checked))
{
return;
}
for(cell = 0; cell< Number(${CELLSUM!'0'}) - 1; cell++)
{
<#--行+列是input的name-->
var name = _this.value + "_" + cell;
var color = document.getElementsByName(name)[0].style.color;
<#--如果有错误 无法选中 返回-->
if(color == "red")
{
_this.checked = false;
alert("此行中有错误数据或必填项未填写,请更改后再导入该条数据!");
return;
}
}
<#--如果没有返回 就选中-->
_this.checked = true;
}
<#--数据表单提交-->
function selfValid()
{
<#--获得多选框总数 作为总行数-->
var rowsum = document.getElementsByName("sca");
if(rowsum ==null)
{
return false;
}
if(rowsum!= null && rowsum.length != 0)
{
for(row = 0; row < rowsum.length; row++)
{
<#--有一行选中 就可以提交-->
if(rowsum[row].checked)
{
return true;
}
}
}
alert("请先选中确定要导入的行");
return false;
}
$(document).ready(function(){
<#--导入成功或失败提示-->
if("${actionmessage!''}" != "null" && "${actionmessage!''}" != "")
alert("${actionmessage!''}");
<#if titleMap?exists && titleMap?size!=0>
warningall();
</#if>
});
<#if titleMap?exists && titleMap?size!=0>
<#--错误显示 载入事件-->
function warningall(){
<#--获得多选框总数 作为总行数-->
var rowsum = document.getElementsByName("sca");
if(rowsum ==null)
return;
if(rowsum!= null && rowsum.length != 0){
for(var row = 0; row < rowsum.length; row++){
for(var cell=0; cell < Number(${CELLSUM!'0'})- 1; cell++)
{
<#--行+列是input的name-->
var name = row + "_" + cell;
warning(document.getElementsByName(name)[0],row);
}
}
}
}
<#-- 非负数-->
var regNum = new RegExp('^[0-9]+(\.[0-9]+)?$');
<#-- 粗略日期-->
var regDate= new RegExp('^(19[5-9]|20[0-5])[0-9]-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2][0-9]|3[01])$');
<#-- 验证提示 参数是input标签-->
function warning(_this,rows)
{
<#-- 获得name 得到列 -->
var cellName = _this.name.split("_")[1];
var value = _this.value;
<#-- 把列转成数字 下面就都根据数字判断 否则根据字符串判断也可以 -->
var _cell = parseInt(cellName, 10);
if(value == null)
return;
<#-- 判断必填项 (判断是去除非必填项)-->
if(_cell != ${titleMap["其它产品名称"]!''} && _cell != ${titleMap["品种(牌号)"]!''} && _cell != ${titleMap["产品的规格型号"]!''} && _cell != ${titleMap["生产批次"]!''} )
{
if(value == "")
{
_this.style.color = "red";
}
else
{
_this.style.color = "black";
}
}
<#--如果产品类别为[预拌混凝土],产品批次不必填-->
else if(_cell == ${titleMap['生产批次']!''}){
<#-- 获得产品类别值 -->
var _value = document.getElementsByName(_this.name.split("_")[0] + "_" + ${titleMap["产品类别"]!''})[0].value;
if(_value != '预拌混凝土' && value == ""){
_this.style.color = "red";
}else{
_this.style.color = "black";
}
}
<#--如果产品名称为[抗渗混凝土],牌号必填-->
else if(_cell == ${titleMap['品种(牌号)']!''}){
<#-- 获取产品名称值 -->
var _value = document.getElementsByName(_this.name.split("_")[0] + "_" + ${titleMap["产品名称"]!''})[0].value;
if(_value == '抗渗混凝土' && value ==""){
_this.style.color = "red";
}else{
_this.style.color = "black";
}
}
<#--如果产品类别为[预拌混凝土],规格型号必填-->
else if(_cell == ${titleMap['生产批次']!''}){
<#-- 获得产品类别值 -->
var _value = document.getElementsByName(_this.name.split("_")[0] + "_" + ${titleMap["产品类别"]!''})[0].value;
if(_value == '预拌混凝土' && value =="" ){
_this.style.color = "red";
}else{
_this.style.color = "black";
}
}
<#-- 判断格式错误 -->
if(value != "")
{
<#-- 日期类型 -->
if(_cell == ${titleMap["材料发货时间"]!''})
{
if(!regDate.exec(value))
_this.style.color = "red";
else
_this.style.color = "black";
}
<#-- 数字类型 -->
else if( _cell == ${titleMap["供应数量"]!''} )
{
if(!regNum.exec(value))
_this.style.color = "red";
else
_this.style.color = "black";
}
<#--合同编号是否在合同信息模块中存在-->
else if(_cell == ${titleMap["合同编号"]!''})
{
regkeyvalue = new RegExp('${contractNos!''}');
//校验合同编号在合同管理模块中是否存在
if(!regkeyvalue.exec(value))
_this.style.color = "red";
else{
_this.style.color = "black";
}
}else if(_cell == ${titleMap["产品类别"]!''}){
var contractno = document.getElementsByName(rows+"_"+0)[0].value;
//根据合同编号contractno 获取该产品类别value 是否在该合同编号中约定
$.ajax({
async:false,
type:"POST",
url: "/supplyinfo/supplyinfo.action?action=validateProTypeByContractNo",
data :{
"contract_no":contractno,
"product_category":value
},
success:function(data){
if(data == 0)
_this.style.color = "red";
else
_this.style.color = "black";
}
});
}else if(_cell == ${titleMap["产品名称"]!''}){
//获取产品类别
var productType = document.getElementsByName(rows+"_"+1)[0].value;
//根据产品类别查询该产品名称是否存在
$.ajax({
async:false,
type:"POST",
url: "/supplyinfo/supplyinfo.action?action=validateSonNameBySuperName",
data :{
"super_name":productType,
"child_name":value,
"col_type":0
},
success:function(data){
if(data == 0)
_this.style.color = "red";
else
_this.style.color = "black";
}
});
}else if(_cell == ${titleMap["产品的规格型号"]!''}){
//获取产品名称
var productName = document.getElementsByName(rows+"_"+2)[0].value;
//产品名称 查询该产品的规格型号是否存在
if( productName!=null ){
$.ajax({
async:false,
type:"POST",
url: "/supplyinfo/supplyinfo.action?action=validateSonNameBySuperName",
data :{
"super_name":productName,
"child_name":value,
"col_type":2
},
success:function(data){
if(data == 0)
_this.style.color = "red";
else
_this.style.color = "black";
}
});
}
}else if(_cell == ${titleMap["品种(牌号)"]!''}){
//获取产品名称
var productName = document.getElementsByName(rows+"_"+2)[0].value;
if( productName!=null && _cell == '无'){
//产品名称 查询该品种牌号是否存在
$.ajax({
async:false,
type:"POST",
url: "/supplyinfo/supplyinfo.action?action=validateSonNameBySuperName",
data :{
"super_name":productName,
"child_name":value,
"col_type":1
},
success:function(data){
if(data == 0)
_this.style.color = "red";
else
_this.style.color = "black";
}
});
}
}else if(_cell == ${titleMap["其它产品名称"]!''}){
//产品类别
var productType = document.getElementsByName(rows+"_"+1)[0].value;
//获取产品名称
var productName = document.getElementsByName(rows+"_"+2)[0].value;
if(productType=='建筑外窗' && productName == '其它' ){
//alert(value);
//判断当其它产品名称不在企业表产品信息中存在
$.ajax({
async:false,
type:"POST",
url: "/supplyinfo/supplyinfo.action?action=validateSonNameBySuperName",
data :{
"child_name":value,
"col_type":-1
},
success:function(data){
if(data == 0)
_this.style.color = "red";
else
_this.style.color = "black";
}
});
}
}
}
}
</#if>
<#--反全选-->
$('input[name=sca]').click(function(){
var ckslength = $('input[name=sca]').length;
if(!$(this)[0].checked){
$('#select')[0].checked = false;
}else if($(this)[0].checked){
if($('input[name=sca]:checked').length == ckslength){
$('#select')[0].checked = true;
}
}
});
</script>
Java代码
/**
* 执行上传操作
* @param access
* @param request
* @param response
* @return
* @throws Wrong
*/
public ModelAndView upload(Access access, HttpServletRequest request,
HttpServletResponse response) throws Wrong {
ModelAndView view = new ModelAndView(
"/interface/supplyinfo/supplyinfo_excel");
// 页面显示提示
String textmessage = "";
// 总行数
int ROWSUM = 104; // 106;
// 总列数
int CELLSUM = 11;
// 数据开始行
int DATACOUNT = 5;
// 日期格式
DateFormat mat = new SimpleDateFormat("yyyy-MM-dd");
// 存放excel所有数据
List<List<String>> rowList = new ArrayList<List<String>>(20);
// 存放excel所有标题位置 key标题名字 value是列位置(从0算起)
Map<String, Integer> titleMap = new HashMap<String, Integer>(33);
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
.getFile("uploadfile");
if (file.getSize() != 0) {
// 获得文件名:
String realFileName = file.getOriginalFilename();
InputStream fileis = null;
try {
// 存放路径
StringBuffer upLoadFilePath = new StringBuffer();
upLoadFilePath
.append(getServletContext().getRealPath("/document"))
.append(File.separator).append("supplyupload")
.append(File.separator);
// 创建路径目录
File tempFilePath = new File(upLoadFilePath.toString());
if (!tempFilePath.exists()) {
tempFilePath.mkdir();
}
Date date = new Date();
String time = mat.format(date);
// 保存 文件名= 路径 + 当前时间 + 上传文件的后缀名(防止路径中有多个. 获取数组最后一个)
File upLoadFile = new File(
upLoadFilePath.toString()
+ time
+ "_"
+ System.currentTimeMillis()
+ "."
+ realFileName.split("\\.")[realFileName
.split("\\.").length - 1]);
FileCopyUtils.copy(file.getBytes(), upLoadFile);
// 重新获得文件流
fileis = new FileInputStream(upLoadFile);
Workbook wb = new HSSFWorkbook(fileis);
Sheet sheet = wb.getSheetAt(0);
// 遍历行数
for (int rowCount = 1; rowCount <= sheet.getLastRowNum(); rowCount++) {
// 获得行 从0行开始
Row row = sheet.getRow(rowCount - 1);
if(row.getRowNum() == 1){
//判断row=1时 材料供应信息表
Cell titlecell = row.getCell(0);
if(!"材料供应信息表".equals(titlecell.getRichStringCellValue()
.toString())){
//判断表头是否为[材料供应信息表]
textmessage = "模板不正确。请重新下载模板";
break;
}
}
// 是数据行
if (rowCount >= DATACOUNT && rowCount <= ROWSUM) {
// 保存列数据
List<String> cellList = new ArrayList<String>(11);
// 遍历列数 不超过CELLSUM最大列
for (int cellCount = 1; cellCount <= sheet
.getLastRowNum() && cellCount <= CELLSUM; cellCount++) {
// 获得列 从0行开始
Cell cell = row.getCell(cellCount - 1);
if (cellCount == 1 || cell == null)
continue;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
// 先看是否是日期格式
if (DateUtil.isCellDateFormatted(cell)) {
// 读取日期格式
String celldate = mat.format(
cell.getDateCellValue()).trim();
cellList.add(celldate);
} else {
// 读取数字
cellList.add(String.valueOf(
cell.getNumericCellValue()).trim());
}
break;
case Cell.CELL_TYPE_STRING:
// 读取String
cellList.add(cell.getRichStringCellValue()
.toString().trim());
break;
case Cell.CELL_TYPE_BLANK:
cellList.add("");
break;
}
}
// 如果cellList不是空 且内容不都是""
if (!cellList.isEmpty()) {
for (String value : cellList) {
if (!"".equals(value)) {
// 保存到行集合
rowList.add(cellList);
break;
}
}
}
} else if(rowCount == 3 && titleMap.size() < CELLSUM - 1){
// 添加列标题 如果titleMap没有添加过的话
for (int cellCount = 1; cellCount <= sheet.getLastRowNum() && cellCount <= CELLSUM; cellCount++){
// 获得列 从0行开始
Cell cell = row.getCell(cellCount - 1);
if (cellCount == 1 || cell == null)
continue;
// 以标题名为key 位置为value(从0开始)
titleMap.put(cell.getRichStringCellValue().toString(), cellCount - 2);
}
}
}
Map<String,Object> enterpriseInfo = this.getEnterpriseInfo(access, request, response);
//获取企业id
Integer enterpriseId = 0 ;
if(enterpriseInfo!=null &&enterpriseInfo.size()>0){
enterpriseId = (Integer)enterpriseInfo.get("enterpriseId");
}
//获取合同编号
List<Map<String, String>> contractnoCommands = access.query(new Declare("contractInfo.select_contractno").AND("enterprise_id = ?", enterpriseId));
view.addObject("textmessage", textmessage);
view.addObject("contractnoCommands",contractnoCommands);
view.addObject("titleMap",titleMap);
view.addObject("titleMaps",titleMap.toString());
view.addObject("rowList", rowList);
view.addObject("CELLSUM", CELLSUM);
}catch (Exception e) {
e.printStackTrace();
}finally{
try{
fileis.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
return view;
}
/**
* 执行导入Excel操作
* */
public ModelAndView importExcel(Access access, HttpServletRequest request,
HttpServletResponse response) throws Wrong {
ModelAndView view = new ModelAndView("commons/reload");
String actionmessage = "导入成功";
try {
String titleMaps = Web.value(request, "titleMaps");
Map<String, Integer> titleMap = (Map<String, Integer> )JSONObject.toBean(JSONObject.fromObject(titleMaps),HashMap.class);
//获取登录用户类型
Integer userType= Web.auth(request).getType();
//获取登录人id
Integer userId= Web.auth(request).getId();
//企业组织机构代码
String unitOrgan = "";
if(userType == 10 ){//企业分帐号
//根据企业分账号查询主企业的组织机构代码
//获取主企业信息
Map<String,Object> mainUnitInfo = access.info3(new Declare("contractInfo.select_mainunit_info").value(userId));
if(mainUnitInfo!=null && mainUnitInfo.size()>0 ){
//获取组织机构代码
unitOrgan =(String) mainUnitInfo.get("com_id");
}
}else{//主企业登录 该功能只有企业才有添加功能
//获取当前用户企业组织机构代码
unitOrgan = Web.auth(request).getAccount();
}
//根据企业组织机构代码企业id
Integer enterpriseId= access.first(new Declare("contractInfo.select_enterprise_id").value(unitOrgan));
//获取当前人id
Integer operateOp = Web.auth(request).getId();
//当前操作人name
String operateName =Web.auth(request).getName();
// 存放所有字段 key是中文名 value是数据库字段名
Map<String, String> filedsMap = Alert.map("合同编号:contract_no,产品类别:product_category,产品名称:product_name,其它产品名称:other_product_name,品种(牌号):variety,产品的规格型号:product_standard,生产批次:product_batch,材料发货时间:approach_date,供应数量:supply_number,计量单位:product_unit");
//产品类别从配置文件combox.properties读取
Map<String, String> productTypeMap = new HashMap<String, String>();
Map<String, String> tempMap = Mix.get().value("productTypeMap", Symbol.Combox);
for (String key : tempMap.keySet())
{
productTypeMap.put(tempMap.get(key), key);
}
// Excel 中需要导入导入的行
String[] check = Web.values(request, "sca");
// 拦截所有异常 任何异常导入失败
try {
for (String row : check) {
StringBuffer sqlfileds = new StringBuffer("");
StringBuffer sqlvalues = new StringBuffer("");
Integer contractId = 0 ;
if (titleMap!=null && titleMap.keySet().size() == 0) {
throw new Exception("读取表格列失败");
}
for (String title : titleMap.keySet()) {
// 获得列位置
int cell = titleMap.get(title);
// 行+列 是input的name
String name = row + "_" + cell;
// 获取值
String value = request.getParameter(name);
if (value != null && !"".equals(value)) {
// 添加第cell个字段
sqlfileds.append(filedsMap.get(title)).append(",");
// 日期类型
if (cell == titleMap.get("材料发货时间")) {
sqlvalues.append("to_date('").append(value)
.append("','yyyy-mm-dd'),");
}
// 数字类型
else if (cell == titleMap.get("供应数量")) {
sqlvalues.append(Double.valueOf(value)).append(
",");
}
// 产品类别存储对应的key
else if (cell == titleMap.get("产品类别")) {
sqlvalues
.append(Alert.number(productTypeMap
.get(value))).append(",");
}else if(cell == titleMap.get("合同编号")){
sqlvalues.append("'").append(value).append("',");
//根据合同编号查询合同表id
contractId =access.first(new Declare("contractInfo.select_contractid").value(value));
}else {
sqlvalues.append("'").append(value).append("',");
}
}
}
//每条进行进行保存
if(sqlfileds!=null && sqlfileds.length()>0 && sqlvalues!=null && sqlvalues.length()>0){
Serializable id = access.append(new Declare("supplyInfo.import_supplyinfo")
.attr("titles", sqlfileds.substring(0,sqlfileds.length()-1))
.attr("values", sqlvalues.substring(0,sqlvalues.length()-1))
.values(enterpriseId,contractId, operateOp, operateName)
);
//-----------计入历史记录表---------|
//定义存储历史表字段
String tableName = this.getEntity().tableName().toUpperCase();//表名
int type = 4;//[1:添加,2:修改,3:删除,4:Excel导入]
//插入历史数据
Bemms.history(access, id, Web.auth(request), tableName, type);
//-----------计入历史记录表---------|
}
}
} catch (Exception e) {
actionmessage = "导入失败,请检查您填写的数据后再重试";
e.printStackTrace();
//事务回滚
access.rollback();
}
} catch (Throwable e) {
throw this.undoErrorMimic(e, this.getMethodLableName("save"));
}
view.addObject("actionmessage",actionmessage);
view.addObject("reload", "/supplyinfo/supplyinfo.action?action=excel&actionmessage="+actionmessage);
return view;
}
展示效果:
Excel模版:(Excel的操作行列是从B5到K104)
进入导入页面:
选择一个正确的文件,点击上传,执行的方法(upload),显示数据,确认导入执行的方法是(importExcel)