导入excel表格demo

 前台:

1、简洁版:

<!--
    文件上传的表单要满足三个条件:
    1、表单组件只能用:<input type="file">
    2、请求方式只能用 post (post除了可以提交文本数据,还能提交 二进制数据)
    3、表单的编码格式只能用:enctype="multipart/form-data"(HTTP协议规定,浏览器每次向后台提交参数,都会对参数进行统一编码)
-->
<div style="margin-top: 100px;margin-left: 600px">
<form action="/importUser" method="post" enctype="multipart/form-data">
    <input type="file" name="userFile"><br>
    <input type="submit" value="提交">
</form>
</div>

2、模态窗口 + 表单验证

<!--导入按钮-->
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#importUserModal" ><span class="glyphicon glyphicon-import"></span> 上传列表数据(导入)</button>
<!--导入用户 模态窗口-->
<div class="modal fade" id="importUserModal"  role="dialog">
    <div class="modal-dialog" role="document" style="width: 60%;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">导入市场活动</h4>
            </div>
            <div class="modal-body" style="height: 350px;">
                <div style="position: relative;top: 20px; left: 50px;">
                    请选择要上传的文件:<small style="color: gray;">[仅支持.xls]</small>
                </div>
                <div style="position: relative;top: 40px; left: 50px;">
                    <input type="file" id="userFile">
                </div>
                <div style="position: relative; width: 400px; height: 320px; left: 45% ; top: -40px;" >
                    <h3>重要提示:</h3>
                    <ul>
                        <li>操作仅针对Excel,仅支持后缀名为XLS的文件。</li>
                        <li>给定文件的第一行将视为字段名。</li>
                        <li>用户密码以字符串形式录入</li>
                        <li>请确认您的文件大小不超过5MB。</li>
                        <li>默认情况下,字符编码是UTF-8 (统一码),请确保您导入的文件使用的是正确的字符编码方式。</li>
                        <li>建议您在导入真实数据之前用测试文件测试文件导入功能。</li>
                    </ul>
                    <ul>
                        <br><h4><span id="msg" style="color: dodgerblue"></span></h4>
                    </ul>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button id="importUserBtn" type="button" class="btn btn-primary">导入</button>
            </div>
        </div>
    </div>
</div>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户信息统计</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.js"></script>
    <script type="text/javascript">
        $(function () {
            //给导入按钮添加单击事件
            $("#importUserBtn").click(function (){
                //收集参数
                //取得文件后缀名
                let userFileName=$("#userFile").val();
                let lastIndex=userFileName.lastIndexOf(".")+1;
                let suffix=userFileName.substr(lastIndex).toLowerCase();
                if (suffix != "xls") {
                    alert("只支持xls文件");
                    return;
                }

                //取得文件本身
                let userFile = $("#userFile")[0].files[0];
                if (userFile.size > 5 * 1024 * 1024) {
                    alert("文件大小不能超过5MB");
                    return;
                }
                console.log(userFile);
                //FormData是ajax提供的接口,可以模拟键值对向后台提交参数;
                let formData = new FormData;
                formData.append("userFile", userFile);

                $("#msg").text("文件导入中......")
                $.ajax({
                    url:'importUser',
                    data:formData,
                    processData:false,//设置ajax向后台提交参数之前,是否把参数统一转换成字符串:true--是,false--不是,默认是true
                    contentType:false,//设置ajax向后台提交参数之前,是否把所有的参数统一按urlencoded编码:true--是,false--不是,默认是true
                    type:'post',
                    dataType:'json',
                    success:function (data) {
                        if (data.state == "200") {
                            alert("成功导入" + data.date + "条记录");
                            $("#importActivityModal").modal("hide");
                            location.reload();
                        }else{
                            alert(data.message);
                            $("#importActivityModal").modal("show");
                        }
                    }
                })
            })
        })
    </script>
</head>

后台:

@RequestMapping("/importUser")
    public @ResponseBody Object importUser(MultipartFile userFile) throws IOException {
        Result result = new Result();
        FileInputStream is = null;
        try {
            String originalFilename = userFile.getOriginalFilename();
            //把接收到的excel文件写到磁盘目录中
            //路径必须手动创建好,这里放在项目resource下
            File file = new File("D:\\.IdeaProjects\\Spring\\csqtest\\src\\main\\resources\\file\\", originalFilename);
            //把文件在服务器指定的目录中生成一个相同的文件(相当于文件传入服务器)

            userFile.transferTo(file);

            //解析excel文件,获取文件数据,并封装在userList中
            is = new FileInputStream("D:\\.IdeaProjects\\Spring\\csqtest\\src\\main\\resources\\file\\" + originalFilename);
            HSSFWorkbook workbook = new HSSFWorkbook(is);
            HSSFSheet sheet = workbook.getSheetAt(0);

            HSSFRow row = null;
            HSSFCell cell = null;
            User user = null;
            List<User> userList = new ArrayList<>();
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                row = sheet.getRow(i);
                //每遍历一行就是一个User对象
                user = new User();

                for (int j = 0; j < row.getLastCellNum(); j++) {
                    cell = row.getCell(j);

                    //HSSFUtils工具类获取列中数据,将数据放入对象中
                    String cellValue = HSSFUtils.getCellValueForStr(cell);
                    if (j == 0) {
                        user.setUsername(cellValue);
                    } else if (j == 1) {
                        user.setPassword(cellValue);
                    }
                }
                //每一行中的所有列都封装完成之后,把user保存到list中,每遍历一行封装一个实体类对象
                userList.add(user);
            }
            //调用service方法批量保存用户
            int ret = userService.saveCreateUserByList(userList);

            result.setState(200);
            result.setMessage("导入成功");
            result.setDate(ret);
        } catch (Exception e) {
            e.printStackTrace();
            result.setState(1001);
            result.setMessage("导入失败");
        } finally {
            is.close();
        }
        return result;
    }

HSSFUtils.getCellValueForStr()工具类方法

public class HSSFUtils {
    /**
     * 从指定的HSSFCell对象中获取列的值
     */
    public static String getCellValueForStr(HSSFCell cell) {
        String ret="";
        if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
            ret= cell.getNumericCellValue()+"";
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
            ret = cell.getStringCellValue();
        } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
            ret = cell.getBooleanCellValue()+"";
        } else {
            ret = "";
        }
        return ret;
    }
}

批量保存方法

@Override
    public int saveCreateUserByList(List<User> list) {
        return userMapper.insertUserByList(list);
    }
    <insert id="insertUserByList" parameterType="com.csq.csqtest.pojo.User">
        insert into `user` (username,password) values
        <foreach collection="list" item="obj" separator=",">
            (#{obj.username},#{obj.password})
        </foreach>
    </insert>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Excel导入导出是Excel软件中非常常见且重要的功能之一。在实际应用开发中,我们常常需要通过程序来实现对Excel文件的导入和导出操作。下面是一个示例的Excel导入导出的Demo源码。 导入功能部分: ```java import java.io.FileInputStream; import java.io.InputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelImportDemo { public static void main(String[] args) { try { // 打开要导入Excel文件 InputStream is = new FileInputStream("导入文件路径"); Workbook workbook = new XSSFWorkbook(is); Sheet sheet = workbook.getSheetAt(0); // 遍历每一行数据 for (Row row : sheet) { // 遍历每个单元格 for (Cell cell : row) { // 将单元格内容输出 System.out.print(cell.getStringCellValue() + "\t"); } System.out.println(); } // 关闭流 workbook.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 导出功能部分: ```java import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExportDemo { public static void main(String[] args) { try { // 创建Excel工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建数据行并填充数据 for (int i = 0; i < 5; i++) { Row row = sheet.createRow(i); for (int j = 0; j < 5; j++) { Cell cell = row.createCell(j); cell.setCellValue("数据" + (i + 1) + "-" + (j + 1)); } } // 保存Excel文件 FileOutputStream fos = new FileOutputStream("导出文件路径"); workbook.write(fos); workbook.close(); fos.close(); System.out.println("导出成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上是一个简单的Excel导入导出的Demo源码,可以帮助你了解如何通过Java代码实现Excel文件的导入和导出功能。你可以根据实际需要进行修改和扩展,以适应更复杂的导入导出操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值