JAVA导入Excel文件_诺贝尔爱情奖的博客-程序员秘密

技术标签: excel  java  

“落叶他乡树,寒灯独夜人”
JSP:

<div id="excelUser" title="excel导入"
     style="display: none; width: 350px; height: 150px; padding: 15px; background: #E9F1FF;">
    <form id="excelUserForm" method="post" enctype="multipart/form-data"
          action="">
        <table cellspacing='0' cellpadding='1'>
            <tr>
                <td style="text-align: left; font-size: 12px;">选择excel文件:</td>
                <td><input style="width: 200px;" type="file"
                           class="input easyui-validatebox" id="excelfile" name="excelfile"
                           required="required" />
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: left; font-size: 12px;"><span
                        style="color: red">注:请选择后缀名为xlsx文件,否则无法导入。</span></td>
            </tr>
        </table>
    </form>
</div>

JS:

/**
 * 上传方法
 */
function doImport() {
    
    $('#excelUser').show().dialog({
        modal : true,
        toolbar : [ {
            text : '提交',
            iconCls : 'icon-ok',
            handler : function() {
    
                $('#excelUserForm').form('submit', {
                    url : 'controller/clientActivityHotInfoManage/import.json',
                    onSubmit : function() {
    
                        parent.$.messager.progress({
                            title : '提示',
                            text : '数据导入中,请稍等....'
                        });
                        var isValid = $('#excelUserForm').form('validate');
                        if (!isValid) {
                            parent.$.messager.progress('close');
                            return false;
                        }
                    },
                    success : function(response) {
    
                        $('#excelUser').dialog('close');
                        var response = eval('(' + response + ')');
                        parent.$.messager.progress('close');
                        if (response.success) {
                            $.messager.alert('成功', response.msg, 'info');
                            $('#subjectGrid').datagrid('reload');
                            // doAuto();

                        } else {

                            $.messager.alert('失败', response.msg, 'error');
                        }
                        $('#projectStageConfig').datagrid('load', {
                            id : $.trim($('#id').val())
                        });
                    },
                    failure : function(response) {
    
                        parent.$.messager.progress('close');
                        $('#excelUser').dialog('close');
                        $.messager.alert('失败', response.msg, 'error');
                    }
                });

            }

        }, {
            text : '关闭',
            iconCls : 'icon-cancel',
            handler : function() {
    
                $('#excelUser').dialog('close');
            }
        } ]

    });
}

Controller:

@CodeComments("导入EXCEL到表中")
    @RequestMapping({
   "/import.json"})
    @ResponseBody
    public void importExcel(MultipartHttpServletRequest request, HttpServletRequest request1, HttpServletResponse response, ClientActivityHotInfoManage eui, Integer egroupid)
    {
        Map messages = new HashMap();
        MultipartFile file = request.getFile("excelfile");
        String inputPath = file.getOriginalFilename();
        System.out.println("inputPath=========================" + inputPath);
        String originalFile = inputPath.substring(
                inputPath.lastIndexOf(".") + 1, inputPath.length())
                .toLowerCase();

        if ("xls,xlsx".indexOf(originalFile) < 0) {
            messages.put("success", Boolean.valueOf(false));
            messages.put("msg", "文件导入类型错误,只能导入后缀名是xlsx的EXCEL文件类型!");
            toJson(response, messages);
            return;
        }
        if ("xls".equals(originalFile)) {
            messages.put("success", Boolean.valueOf(false));
            messages.put("msg", "文件导入类型错误,只能导入后缀名是xlsx的EXCEL文件类型!");
            toJson(response, messages);
            return;
        }
        if (file.getSize() > 20048576L) {
            messages.put("success", Boolean.valueOf(false));
            messages.put("msg", "文件过大,只能导入20M内文件!");
            toJson(response, messages);
            return;
        }

        int i = 0;
        try
        {
            InputStream fis = file.getInputStream();
        //这个方法在下面展示
            List imielist = ActivityHotInfoExcelManage.importExcelInfo(fis, eui);

            ClientActivityHotInfoManage order = new ClientActivityHotInfoManage();


            for (i = 0; i < imielist.size(); i++)
            {
                ClientActivityHotInfoManage vo = (ClientActivityHotInfoManage)imielist.get(i);
                ClientActivityHotInfoManage lx = new ClientActivityHotInfoManage();

                lx.setAcId(vo.getAcId());
                lx.setAcUrl(vo.getAcUrl());
                lx.setStartDate(vo.getStartDate());
                lx.setEndDate(vo.getEndDate());
                lx.setRepeat(vo.getRepeat());
                lx.setStatus(vo.getStatus());
                lx.setPlotId(vo.getPlotId());
                lx.setAcName(vo.getAcName());


//这里就可以直接插入实体类了             this.clientActivityHotInfoManageService.insert(lx);

                messages.put("success", Boolean.valueOf(true));
                messages.put("msg", "数据导入成功!");
            }
            fis.close();
        }
        catch (Exception e) {
            messages.put("success", Boolean.valueOf(false));
            messages.put("msg", "导入异常,请在检查excel表的第" + (i + 2) + "行后,从第" + (
                    i + 2) + "行开始导入!");
            System.out.println("importExcel异常--------->" + e.getMessage());
        }
        toJson(response, messages);
    }

importExcelInfo方法

public static List<ClientActivityHotInfoManage> importExcelInfo(InputStream fis, ClientActivityHotInfoManage eui)
    {
        List<ClientActivityHotInfoManage> excelInfos = new ArrayList<ClientActivityHotInfoManage>();
        try
        {
            XSSFWorkbook hwb = new XSSFWorkbook(fis);

            XSSFSheet sheet = hwb.getSheetAt(0);
            XSSFRow row = null;

            System.out.println("*****总行数****" + sheet.getPhysicalNumberOfRows());

            for (int i = 0; i < hwb.getNumberOfSheets(); i++) {
    
                sheet = hwb.getSheetAt(i);

                for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++)
                {
                    row = sheet.getRow(j);
                    ClientActivityHotInfoManage excelInfo = new ClientActivityHotInfoManage();

                    if ((row.getCell(1) != null) &&
                            (getCellValue(row.getCell(1)) != "")) {

                        excelInfo.setAcId(getCellValue(row.getCell(1)).trim());
                        excelInfo.setAcUrl(getCellValue(row.getCell(2)).trim());
                        excelInfo.setStartDate(getCellValue(row.getCell(3)).trim());
                        excelInfo.setEndDate(getCellValue(row.getCell(4)).trim());
                        excelInfo.setRepeat(Long.parseLong(getCellValue(row.getCell(5)).trim().substring(0,1)));
                        excelInfo.setStatus(Long.parseLong(getCellValue(row.getCell(6)).trim().substring(0,1)));
                        excelInfo.setPlotId((getCellValue(row.getCell(7)).trim()));
                        excelInfo.setAcName((getCellValue(row.getCell(8)).trim()));
                    }

                    excelInfos.add(excelInfo);
                }

            }

            return excelInfos;
        }
        catch (Exception e) {
            System.out.println("导入EXCEL文件出错------------>" + e.getMessage());
        }
        return null;
    }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/A_Runner/article/details/78205179

智能推荐

iOS开发UIscrollview常用属性方法_aboi22699的博客-程序员秘密

//// ViewController.m// ScrollviewAll#import "ViewController.h"@interface ViewController ()&lt;UIScrollViewDelegate&gt;@[email protected] ViewController- (void)viewDi...

ML Note 3 - Unsupervised Learning_LutingWang的博客-程序员秘密

机器学习笔记 3本文为吴恩达老师 CS229 课程笔记,包括无监督学习的部分内容。即 k-means 算法、EM 算法、主成分分析等。

VMW15虚拟机安装macOS_This_is_myl的博客-程序员秘密

这篇文章是我看了很多大神的文章然后汇集了一些内容编辑而成的。废话不多说,先放上工具列表VMW15:网上有很多的安装包和注册码,那就不用我放链接了Unlocker:用来破解VMW的,让虚拟机能够识别mac系统macOS镜像文件:这个就不用我说了darwin.iso文件这个链接里有Unlocker文件和macOS 10.4镜像文件(注意:链接里的macOS镜像文件下载完以后后缀需要改为.i...

HttpClientFactory 使用说明 及 对 HttpClient 的回顾和对比_dotNET跨平台的博客-程序员秘密

在 C# 中,平时我们在使用 HttpClient 的时候,会将 HttpClient 包裹在 using 内部进行声明和初始化,如:using(var httpClie...

k8s学习 ---网络插件的安装_ppplaybook的博客-程序员秘密

文章目录flannel镜像flannel配置文件flannel镜像#每个节点都需要拉取镜像docker pull lwolf/flannel:v0.12.0docker tag lwolf/flannel:v0.12.0 quay.io/coreos/flannel:v0.12.0-amd64flannel配置文件

随便推点

MySQL ERROR 1064 (42000)_error1064_JustDoDT的博客-程序员秘密

今天笔者写了一条SQL 语句,不管怎么修改始终报错,可是也没有找到原因,后来才发现是语法的错误。CREATE TABLE 't'( 'a' int(11) NOT NULL auto_increment, 'b' varchar(20) DEFAULT NULL, PRIMARY KEY ('a'), KEY 'b' ('b') ) ENGINE=InnoDB auto_increment=1...

Android 通过Http请求网络获取图片资源_残风乱了温柔的博客-程序员秘密

    在日常的编写Android软件的过程中,避免不了使用网络请求,但是发http请求是不能在主线程里面发,否则就会出现android.os.NetworkOnMainThreadException的异常,所以必须要放到子线程中处理。步骤如下:       1、将想要请求的图片地址转换成URL类  2、通过openConnection来建立连接  3、在编程的时候避免让用户等,设置网...

hadoop HA总结_weixin_39182877的博客-程序员秘密

1.SNN  checkpoint 多久?什么参数配置?参数在哪?60分钟,dfs.namenode.checkpoint.period , hdfs-default.xml 2.ZooKeeper是做什么的?协调服务、统一命名服务、状态同步服务、集群管理、分布式应用配置项的管理等3.ZooKeeper的作用?Zookeeper 作为一个分布式的服务框架,主要用来解决分布式集群中应用系统的一致性问...

LSH系列概述:局部敏感哈希(Locality-Sensitive Hashing, LSH)方法介绍_适配lsh的hash函数_Tcorpion的博客-程序员秘密

转载来源:http://blog.csdn.net/icvpr/article/details/12342159局部敏感哈希(Locality-Sensitive Hashing, LSH)方法介绍本文主要介绍一种用于海量高维数据的近似最近邻快速查找技术——局部敏感哈希(Locality-Sensitive Hashing, LSH),内容包括了LSH的原理、LSH

导出mongodb数据库中的数据,并存成json文件形式或csv文件形式_風中塵埃的博客-程序员秘密

数据库名和collections名:命令格式:mongoexport -d 数据库名 -c collections的名字 -o filename.json/filename.csv -f field参数说明:1. -d 数据库名(database)2. -c collections名3. -o 要存入的文件名(xxx.json/xxx.csv)4. -f ...

【Java学习笔记之二】java标识符命名规范_weixin_34232363的博客-程序员秘密

什么是标识符就是程序员在定义java程序时,自定义的一些名字。标识符可以应用在类名、变量、函数名、包名上。标识符必须遵循以下规则标识符由26个英文字符大小写(a~zA~Z)、数字(0~9)、下划线(_)和美元符号($)组成。不能以数字开头,不能是关键字严格区分大小写标识符的可以为任意长度Java中的标识符命名规范1. 包名...