zhaohz

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 首先到官网把插件下载下来

git clone https://github.com/kartik-v/bootstrap-fileinput.git

2. 将文件导入到工程,在前端页面将插件引入

<link rel="stylesheet" href="${basePath}/resources/plugs/bootstrap-fileinput/css/fileinput.min.css"/>
<script src="${basePath}/resources/plugs/bootstrap-fileinput/js/fileinput.min.js"></script>
<script src="${basePath}/resources/plugs/bootstrap-fileinput/js/locales/zh.js"></script>

 3. 导入界面

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
        <li class="fa fa-remove"></li>
    </button>
    <h5 class="modal-title">Excel文件上传</h5>
</div>
<div class="modal-body">
    <form id="importFile" name="importFile" class="form-horizontal" method="post"
          enctype="multipart/form-data">
        <div class="box-body">
            <div>
                <label class="control-label">请选择要导入的Excel文件:</label>
                <input id="excelFile" name="excelFile" class="file-loading" type="file" multiple accept=".xls,.xlsx"
                       > <br>
            </div>
        </div>
    </form>
</div>

4. js处理

<script>
    initUpload("excelFile", basePath + "/test/upload");
    function initUpload(ctrlName, uploadUrl) {
        var control = $('#' + ctrlName);
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: uploadUrl, //上传的地址
            uploadAsync: true, //默认异步上传
            showCaption: true,//是否显示标题
            showUpload: true, //是否显示上传按钮
            browseClass: "btn btn-primary", //按钮样式
            allowedFileExtensions: ["xls", "xlsx"], //接收的文件后缀
            maxFileCount: 10,//最大上传文件数限制
            previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
            showPreview: true, //是否显示预览
            previewFileIconSettings: {
                'docx': '<i ass="fa fa-file-word-o text-primary"></i>',
                'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'jpg': '<i class="fa fa-file-photo-o text-warning"></i>',
                'pdf': '<i class="fa fa-file-archive-o text-muted"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
            },
            uploadExtraData: function () {
                var extraValue = "test";
                return {"excelType": extraValue};
            }
        });
    }
    $("#excelFile").on("fileuploaded", function (event, data, previewId, index) {
        console.log(data);
        if(data.response.success == true)
        {
            alert(data.files[index].name + "上传成功!");
	    //关闭
            $(".close").click();
        }
        else{
            alert(data.files[index].name + "上传失败!" + data.response.message);
	    //重置
	    $("#excelFile").fileinput("clear");
	    $("#excelFile").fileinput("reset");
	    $('#excelFile').fileinput('refresh');
	    $('#excelFile').fileinput('enable');
        }
    });
</script>

5.  后台接口

   @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    private Result importExcel(@RequestParam(value = "excelFile", required = false) MultipartFile file,HttpServletRequest request) {
        try {
            MultipartRequest multipartRequest=(MultipartRequest) request;
            MultipartFile excelFile=multipartRequest.getFile("excelFile");
            if(excelFile!=null){
                List<List<String>> datas = ExcelUtil.readXls(excelFile.getInputStream());
		//TODO: 读到的数据都在datas里面,根据实际业务逻辑做相应处理
// ............. if(datas!=null && datas.size()>0){ return new Result(true); } }else{ return new Result(false); } } catch (Exception e) { return new Result(false,e.getMessage()); } return new Result(false); }

6. 附ExcelUtil类

package com.cnpc.framework.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class ExcelUtil {
    public static List<List<String>> readXlsx(String path) throws IOException {
        InputStream input = new FileInputStream(path);
        return readXlsx(input);
    }

    public static List<List<String>> readXls(String path) throws IOException {
        InputStream input = new FileInputStream(path);
        return readXls(input);
    }

    public static List<List<String>> readXlsx(InputStream input) throws IOException {
        List<List<String>> result = new ArrayList<List<String>>();
        XSSFWorkbook workbook = new XSSFWorkbook(input);
        for (XSSFSheet xssfSheet : workbook) {
            if (xssfSheet == null) {
                continue;
            }
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow row = xssfSheet.getRow(rowNum);
                int minCellNum = row.getFirstCellNum();
                int maxCellNum = row.getLastCellNum();
                List<String> rowList = new ArrayList<String>();
                for (int i = minCellNum; i < maxCellNum; i++) {
                    XSSFCell cell = row.getCell(i);
                    if (cell == null) {
                        continue;
                    }
                    rowList.add(cell.toString());
                }
                result.add(rowList);
            }
        }
        return result;
    }

    public static List<List<String>> readXls(InputStream input) throws IOException {
        List<List<String>> result = new ArrayList<List<String>>();
        HSSFWorkbook workbook = new HSSFWorkbook(input);
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet sheet = workbook.getSheetAt(numSheet);
            if (sheet == null) {
                continue;
            }
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                HSSFRow row = sheet.getRow(rowNum);
                int minCellNum = row.getFirstCellNum();
                int maxCellNum = row.getLastCellNum();
                List<String> rowList = new ArrayList<String>();
                for (int i = minCellNum; i < maxCellNum; i++) {
                    HSSFCell cell = row.getCell(i);
                    if (cell == null) {
                        continue;
                    }
                    rowList.add(getStringVal(cell));
                }
                result.add(rowList);
            }
        }
        return result;
    }

    private static String getStringVal(HSSFCell cell) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_BOOLEAN:
                return cell.getBooleanCellValue() ? "TRUE" : "FALSE";
            case Cell.CELL_TYPE_FORMULA:
                return cell.getCellFormula();
            case Cell.CELL_TYPE_NUMERIC:
                cell.setCellType(Cell.CELL_TYPE_STRING);
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            default:
                return null;
        }
    }

}

  


  

posted on 2017-07-30 14:44  zzhaoh  阅读(13017)  评论(2编辑  收藏  举报