jsp页面导入excel文件的步骤及配置

上传使用flash插件

需要jquery.uploadify.min.js,uploadify.css,poi-ooxml-3.8-20120326.jar等

jsp页面:

<%@include file="/uploadDeclare.jsp"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.uploadify {
    float: left;
    margin: 0 10px;
}
</style>
<script type="text/javascript">
//导入功能
$(function() {
    $("#uploadFile").uploadify({
        buttonClass : ‘‘,
        fileSizeLimit : ‘51200KB‘,
        uploader : ‘${basePath}core/upload!uploadFile.action‘, // 服务器端处理地址
        swf : ‘${basePath}js/uploadify/uploadify.swf‘, // 上传使用的 Flash
        buttonText : "导入",
        buttonCursor : ‘hand‘,
        fileObjName : ‘uploadify‘,// 上传参数名称 后台action里面的属性uploadify
        fileTypeExts : "*.xls;*.xlsx", // 扩展名
        fileTypeDesc : "请选择 文件格式",
        removeTimeout : 1, // 文件说明
        auto : true, // 选择之后,自动开始上传
        multi : false, // 是否支持同时上传多个文件
        queueSizeLimit : 1, // 允许多文件上传的时候,同时上传文件的个数
        queueID : ‘queueID‘,

        onUploadSuccess : function(file, data, response) {
            var data = jQuery.parseJSON(data);
            if (data.error == 1) {
                ldDialog.alert(data.message);
            } else {
                $.ajax({
                    url : "${basePath}uploadDocumentAction/uploadDocument!importManyOverallPlan.action",
                    type : "post",
                    dataType : "json",
                    data : {
                        filePath : data.url,
                        fileName : data.newFileName,
                        proId : "${proId}",
                    },
                    async : false,
                    success : function(r) {
                        if (r.code == ‘success‘) {
                            ldDialog.tips("导入成功!");
                            document.pagerForm.submit();
                        } else {
                            ldDialog.tips("导入失败!");
                        }
                    }
                });
            }
        }
    });
});
</script>
</head>

<td>
     <input type="button" id="uploadFile" class="ldBtnGray" value="导入" />&nbsp;&nbsp;
     <a href="${basePath}/upload/template/template13.xlsx" download="template13.xlsx">
         <span style=‘float: right; margin-right: 20px; margin-top: 10px; font-size: 18px; color: #2891d2;‘>模板下载</span>
     </a>
</td> 

uploadDeclare.jsp

<%@page language="java" contentType="text/html; charset=utf-8"%>
<base
    href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
<LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript">
    //防止客户端缓存文件,造成uploadify.js不更新,而引起的“喔唷,崩溃啦”
    document.write ("<script type=‘text/javascript‘ " + "src=‘${basePath}plugins/uploadify/jquery.uploadify.min.js?" + new Date () + "‘><\/script>");
</script>
<style>
.uploadify-box {
    width: 130px;
    margin: 0px;
    margin-top: 10px;
}
</style>

效果页面:

excel文件放在eclipse-workspace\report\WebRoot\upload\template\template13.xlsx目录下,都有的字段:

jsp页面 url : "${basePath}uploadDocumentAction/uploadDocument!importManyOverallPlan.action"对应的类,uploadDocumentAction

其中base类DesigndrawOverallPlanPo中书协的属性和属性的get(),set()方法,可自行编写

    /**
     * 批量导入
     * @param modelMap
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("uploadDocument!importManyOverallPlan.action")
    public JSONObject importManyOverallPlan(ModelMap modelMap, HttpServletRequest request) throws ParseException {
        String filePath = this.getStringParameter("filePath");
        String fileName = this.getStringParameter("fileName");
        String proId = this.getStringParameter("proId");
        final JSONObject result = new JSONObject();
        final UploadDocument uploadDocument = this.parameterToPoPrefix(UploadDocument.class);
        ProApprovalPo proApproval = this.proApprovalBaseService.queryProApprovalById(proId);
        User user = this.getSessionUser();
        String proName = "";
        boolean success = false;
        String code = "";

        if(user != null && proApproval != null) {
            String abPath = request.getSession().getServletContext().getRealPath("/");
            filePath = abPath + filePath;
            List<DesigndrawOverallPlanPo> designdrawOverallPlans = new ReadInfoTableExcel().getExcelToOverallPlan(filePath);
            proName = proApproval.getProName();
            for(int i=0;i<designdrawOverallPlans.size();i++) {
                DesigndrawOverallPlanPo designdrawOverallPlan = designdrawOverallPlans.get(i);
                //首先校验excel文件中的项目id和项目名称是否正确
                //还有计划开始时间要小于等于计划结束时间
                //且时间格式2018-01-02要正确
                //计划开始时间和计划结束时间是date类型与导入时类型(java.long.String)不匹配,
                //所以现在导入时,计划开始时间值:reserved1,计划结束时间:reserved2
                //.trim():取消空格
                if(StringUtils.isEmpty(designdrawOverallPlan.getProId()) || !proId.equals(designdrawOverallPlan.getProId().trim())) {
                    continue;
                }else if(StringUtils.isEmpty(designdrawOverallPlan.getProName()) || !proName.equals(designdrawOverallPlan.getProName().trim())) {
                    continue;
                }else if(StringUtils.isNotEmpty(designdrawOverallPlan.getReserved1()) && StringUtils.isNotEmpty(designdrawOverallPlan.getReserved2())) {
                    java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
                    String startAcTime = designdrawOverallPlan.getReserved1().trim();
                    String endAcTime = designdrawOverallPlan.getReserved2().trim();
                    //计算持续时长(天):计划结束时间-计划开始时间
                    if(validationTimeFormat(startAcTime) && validationTimeFormat(endAcTime)) {
                        int day = (int)((format.parse(endAcTime).getTime() - format.parse(startAcTime).getTime())/(24 * 60 * 60 * 1000)) + 1;
                        if(day<1) {
                            continue;
                        }else {
                            designdrawOverallPlan.setStartAcTime(format.parse(startAcTime));
                            designdrawOverallPlan.setEndAcTime(format.parse(endAcTime));
                            designdrawOverallPlan.setContinueDate(day);
                        }
                    }
                }
                designdrawOverallPlan.setReserved1(null);
                designdrawOverallPlan.setReserved2(null);
                designdrawOverallPlan.setProId(designdrawOverallPlan.getProId().trim());
                designdrawOverallPlan.setProName(designdrawOverallPlan.getProName().trim());
                designdrawOverallPlan.setBaseInfo(user);
                designdrawOverallPlanBaseService.insertDesigndrawOverallPlan(designdrawOverallPlan);
                success = true;
            }
        }
        result.put("code", code);
        return result;
    }
    /**
     * 校验时间格式为2018-01-02
     * @param time
     * @return
     */
    public boolean validationTimeFormat(String time) {
        boolean bool = false;
        Pattern pattern = Pattern.compile("[0-9]*");
        if(time != null && time.length() == 10) {
            //校验前四位是否为数字
            if(pattern.matcher(time.substring(0, 4)).matches()) {
                //校验第五位是-
                if("-".indexOf(time.substring(4, 5))!=-1) {
                    //校验第6,7位是否为数字
                    if(pattern.matcher(time.substring(5,7)).matches()) {
                        //校验第8位是否为-
                        if("-".indexOf(time.substring(7, 8))!=-1) {
                            //校验第9,10位是否为数字
                            if(pattern.matcher(time.substring(8, 10)).matches()) {
                                bool = true;
                            }
                        }
                    }
                }
            }

        }
        return bool;
    }

方法:ReadInfoTableExcel().getExcelToOverallPlan(filePath);

 /**
     *     获取excel里的信息
     * @param filepath
     * @param filetype
     * @param uuid
     * @return
     */
    public List<DesigndrawOverallPlanPo> getExcelToOverallPlan(String filePath) {
        //这儿导入使用两个方法原因:
        //excel版本有03版本和07版本的区别,文件后缀名分别为.xls和.xlsx。它们对应的POI中的Workbook也是不同的,
        //分别是HSSFWorkbook和XSSFWorkbook;对于不同版本的EXCEL文档要使用不同的工具类
        try{
            return addExcelToOverallPlanXSSF1(filePath);
        }catch(Exception e){
            try{
                return addExcelToOverallPlanXSSF2(filePath);
            }catch (Exception e1){
                return null;
            }
        }
    }

方法:addExcelToOverallPlanXSSF1 和 addExcelToOverallPlanXSSF2,这儿利用到了反射的方法使属性和字段值一一对应起来。

  /**
     *  批量导入 方法1
     * @param filePath
     * @return
     * @throws IOException
     */
    public List<DesigndrawOverallPlanPo> addExcelToOverallPlanXSSF1(String filePath) throws IOException{
        List<ZuobiaoInfo> zuobiaoInfos = new ArrayList<>();
        List<DesigndrawOverallPlanPo> designdrawOverallPlans = new ArrayList<DesigndrawOverallPlanPo>();
        XSSFWorkbook swb = new XSSFWorkbook(filePath);
        XSSFSheet sheet = swb.getSheetAt(0);
        zuobiaoInfos = new TableinfoTest().getOverallPlan();
        //获取excel文件中的行数
        int rowsNumber = this.getnumber(filePath);
        for(int i=0;i<rowsNumber;i++) {
            boolean flag = true;
            DesigndrawOverallPlanPo designdrawOverallPlan = new DesigndrawOverallPlanPo();
            for(int j=0;j<zuobiaoInfos.size();j++) {
                Class c = designdrawOverallPlan.getClass();
                Class[] cargs = new Class[1];
                int cellnumber = zuobiaoInfos.get(j).getZongzuobiao();
                try {
                    Object realArgs = this.getXSSFSheetExcelvalue(i+1, cellnumber, sheet);
                    if(realArgs!=null) {
                        cargs[0] = realArgs.getClass();
                        String method = zuobiaoInfos.get(j).getMethod();
                        Method m = c.getMethod(method, cargs);
                        Object[] inArgs = new Object[1];
                        inArgs[0] = realArgs;
                        m.invoke(designdrawOverallPlan, inArgs);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    flag = false;
                    break;
                }
            }
            if(flag) {
                designdrawOverallPlans.add(designdrawOverallPlan);
            }
        }
        return designdrawOverallPlans;
    }
    /**
     *  批量导入 方法2
     * @param filePath
     * @return
     * @throws IOException
     */
    public List<DesigndrawOverallPlanPo> addExcelToOverallPlanXSSF2(String filePath) throws IOException{
        List<ZuobiaoInfo> zuobiaoInfos = new ArrayList<>();
        List<DesigndrawOverallPlanPo> designdrawOverallPlans = new ArrayList<DesigndrawOverallPlanPo>();
        HSSFWorkbook xwb = new HSSFWorkbook(new FileInputStream(filePath));
        HSSFSheet sheet= xwb.getSheetAt(0);
        zuobiaoInfos = new TableinfoTest().getOverallPlan();
        //获取excel文件中的行数
        int rowsNumber = this.getnumber(filePath);
        for(int i=0;i<rowsNumber;i++) {
            boolean flag = true;
            DesigndrawOverallPlanPo designdrawOverallPlan = new DesigndrawOverallPlanPo();
            for(int j=0;j<zuobiaoInfos.size();j++) {
                Class c = designdrawOverallPlan.getClass();
                Class[] cargs = new Class[1];
                int cellnumber = zuobiaoInfos.get(j).getZongzuobiao();
                try {
                    Object realArgs=this.getHSSFSheetExcelvalue(i+1, cellnumber, sheet);
                    if(realArgs!=null) {
                        cargs[0] = realArgs.getClass();
                        String method = zuobiaoInfos.get(j).getMethod();
                         if(!realArgs.toString().equals("")){
                                Method m = c.getMethod(method, cargs);
                                Object[] inArgs = new Object[1];
                                inArgs[0] = realArgs;
                                m.invoke(designdrawOverallPlan, inArgs);
                            }else{
                                flag = false;
                                break;
                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    flag = false;
                    break;
                }
            }
            if(flag) {
                designdrawOverallPlans.add(designdrawOverallPlan);
            }
        }
        return designdrawOverallPlans;
    }

方法:this.getnumber(filePath);

 public int getnumber(String filepath)  {

        try{
            XSSFWorkbook xwb = new XSSFWorkbook(filepath);
            XSSFSheet sheet = xwb.getSheetAt(0);
            int allsheetnumber=sheet.getLastRowNum();
            System.out.println(allsheetnumber);
            return allsheetnumber;
        }catch (Exception e){
            e.printStackTrace();
            try {

                HSSFWorkbook xwb1 = new HSSFWorkbook(new FileInputStream(filepath));
                HSSFSheet sheet1= xwb1.getSheetAt(0);
                int allsheetnumber1=sheet1.getLastRowNum();
                return allsheetnumber1;
            }catch (Exception e1){
                e1.printStackTrace();
                return 0;
            }
        }

    }

方法:this.getHSSFSheetExcelvalue(i+1, cellnumber, sheet);

 public String getHSSFSheetExcelvalue(int rownumber,int cellnumber,HSSFSheet sheet){
        String str=null;
        if(sheet.getRow(rownumber)!=null){
            if(sheet.getRow(rownumber).getCell(cellnumber)!=null){
                str=sheet.getRow(rownumber).getCell(cellnumber).toString();
            }
        }
        return str;
     }

方法:TableinfoTest().getOverallPlan(),其中setProId等是base类DesigndrawOverallPlanPo中属性proId的set()方法。

public class TableinfoTest {
 List<ZuobiaoInfo> overallPlan = new ArrayList<ZuobiaoInfo>
    (Arrays.asList(
        new ZuobiaoInfo("setProId", "项目编号", 0),
        new ZuobiaoInfo("setProName", "项目名称", 1),
        new ZuobiaoInfo("setWorkContent", "工作内容", 2),
        new ZuobiaoInfo("setReserved1", "计划开始时间", 3),
        new ZuobiaoInfo("setReserved2", "计划结束时间", 4),
        new ZuobiaoInfo("setRemarks", "备注", 5)
    ));
    public List<ZuobiaoInfo> getOverallPlan() {
        return overallPlan;
    }

    public void setOverallPlan(List<ZuobiaoInfo> overallPlan) {
        this.overallPlan = overallPlan;
    }

}

类:ZuobiaoInfo

package com.landicorp.pilot.action.readexcel;

public class ZuobiaoInfo {

    public String Method;//方法名
    public String name;
    public int zongzuobiao;//纵坐标

     public ZuobiaoInfo(){

    }
     public ZuobiaoInfo(String Method, String name ,int zongzuobiao){
         this.Method=Method;
         this .zongzuobiao=zongzuobiao;
         this .name=name;
     }
    public int getZongzuobiao() {
        return zongzuobiao;
    }
    public void setZongzuobiao(int zongzuobiao) {
        this.zongzuobiao = zongzuobiao;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getMethod() {
        return Method;
    }

    public void setMethod(String method) {
        Method = method;
    }

}

原文地址:https://www.cnblogs.com/lxnlxn/p/10253727.html

时间: 2024-09-30 15:49:07

jsp页面导入excel文件的步骤及配置的相关文章

基于yaf框架和uploadify插件,做的一个导入excel文件,查看并保存数据的功能

思路: 1.首先,页面前端,上传附件,提交给后台,并带一个随机性的参数(可以用时间戳): 2.后端接收附件,做一系列的逻辑处理,无误后,将对应的文件存储在上传的目录下: 3.然后前端,上传附件成功后,进行请求后端,读取数据,后端接口对应将附件数据读取出来,前端进行显示(ajax请求): 4.前端展示数据,用户对数据检测无误,点击保存(ajax请求后端保存代码的接口),当然也可以有选择性的选择某些数据记录进行保存,楼主这里做的是全部保存(后端处理接口,自动过滤重复数据): 5.拿到对应的所需有用数

jeecg3.5中的导入excel文件的使用及完善

jeecg中导入导出excel文件使用了jeecg团队自己开发的一个easypoi库,所以使用起来非常简单,以我项目中导入黑名单列表功能为例: 在实体中增加注解 先增加类的注解: @ExcelTarget("blackListEntity") public class BlackListEntity implements java.io.Serializable { 再增加字段注解: /**手机号码*/ @Excel(name="手机号码") private Lon

Yii 2 &mdash;&mdash; 导入Excel文件

导入Excel文件需要两个扩展:PHPOffice/PHPExcel和moonlandsoft/yii2-phpexcel,这两个扩展中,PHPOffice/PHPExcel是基础的Excel文件接口,moonlandsoft/yii2-phpexcel提供了导入和导出的功能. 引入PHPOffice/PHPExcel 官网地址: https://github.com/PHPOffice/PHPExcel 下载后解压,拷贝到vendor/PHPExcel目录下,整体目录结构如下: PHPExce

YII使用PHPExcel导入Excel文件的方法

1.下载phpexcel,将压缩包中的classes复制到protected/extensions下并修改为PHPExcel. 2.修改YII配置文件config/main.php [php] view plaincopy 'import'=>array( 'application.extensions.PHPExcel.PHPExcel', ), (以下处理PHPExcel autoload和YII autoload相冲突的方法任选其一,推荐第4种,最符合YII标准) 3.1.修改PHPExc

Java POI导入Excel文件

今天在公司需要做个导入Excel文件的功能,所以研究了一下,参考网上的一些资料总算是做出来了,在此记录一下防止以后忘记怎么弄. 本人用的是poi3.8,所以需要的JAR包如下: poi-3.8.jar poi-excelant-3.8-20120326.jar poi-ooxml-3.8-20120326.jar poi-ooxml-schemas-3.8-20120326.jar poi-scratchpad-3.8-20120326.jar xmlbeans-2.3.0.jar 附上百度云盘

django 导入Excel文件 ORM 批量操作

导入excel文件后批量插入"bulk_create"方法 1.先定义数据模型 from django.db import models from django.utils.translation import ugettext_lazy as _ ACTIVE_TYPE = ( (1, _(u"已激活")), (0, _(u"未激活")), ) class Unit(models.Model): """ 社会单位

Java导入Excel文件

package com.cme.core; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Ar

excel数据 入库mysql 和 mysql数据 导入excel文件

1.excel数据入库mysql 首先准备excel文件, 标红的地方需要留意,一个是字段名所在行,一个表名对应页: 然后私用mysql工具 navicat, 选择数据库,然后导入文件, 选中相应execl文件,即可导入. 栏位名行  对应excel文件中,字段名所在的行. 第一个数据行  对应excel文件中,第一行数据所在的行. ----------------------------------------------------------------------------------

利用kettle组件导入excel文件到数据库

1.     实现目标 把excel文件内容导入到目标表中:然后用java调用kettle的转换.excel文件的内容仅仅有两列,示比例如以下: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbmV3ZWFzdHN1bg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" > 数据库表的结构例如以下: watermark/2/text/aHR0