java+layui实现excel文件的模板下载和导入

因为layui表格自带导出功能,所以就不再做导出功能

相关pom文件



    org.apache.poi
    poi
    4.0.0


    org.apache.poi
    poi-ooxml
    4.0.0

前端代码


    

点击上传,或将文件拖拽到此处


上传成功后渲染

前端js

 layui.use(['form','upload'], function () {
        var form = layui.form;
        var upload = layui.upload;//上传

        //拖拽上传
        upload.render({
            elem:'#excel'
            ,url:'student/excelImportStudent'
            ,accept:'file'
            ,done: function (res) {
                layer.msg(res.msg);
                console.log(res);
            }
        });

后端controller

//excel的拖拽和点击上传
    @RequestMapping("/excelImportStudent")
    @ResponseBody
    public DataView excelImportStudent(@RequestParam("file") MultipartFile file) throws Exception{
        DataView dataView  = new DataView();
        //文件不能为空
        if(file.isEmpty()){
            dataView.setMsg("文件为空,不能上传");
        }
        //poi获取excel
        XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = wb.getSheetAt(0);
        //定义一个程序集合,接受文件中的数据
        List list = new ArrayList<>();
        XSSFRow row = null;
        //解析数据,装到集合里面
        for(int i = 0;ipublic interface StudentService extends IService{
void download(OutputStream os, InputStream bis);
}

serviceImpl

@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl implements StudentService {
 @Override
    public void download(OutputStream os, InputStream bis) {
        try{
            XSSFWorkbook workbook = new XSSFWorkbook(bis);
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

别忘了给实体类添加

@TableId(value = "id",type = IdType.AUTO)

让主键id通过自增方式,不加的话会导致接口异常,导入不进去。

你可能感兴趣的:(java项目,java,layui,excel)