java实现将excle数据导入到web页面

1.Service实现类

@Override
    public List<ListExcle> loadScoreInfo(String xlsPath) throws IOException {
        List<ListExcle> temp = new ArrayList<ListExcle>();
        FileInputStream fileIn = new FileInputStream(xlsPath);
        //根据指定的文件输入流导入Excel从而产生Workbook对象
        HSSFWorkbook wb0 = new HSSFWorkbook(fileIn);
        //获取Excel文档中的第一个表单
        HSSFSheet sht0 = wb0.getSheetAt(0);
        //对Sheet中的每一行进行迭代
        for (Row r : sht0) {
        //如果当前行的行号(从0开始)未达到2(第三行)则从新循环
        if(r.getRowNum()<1){
        continue;
        }
        //创建实体类
        ListExcle info=new ListExcle();
        //取出当前行第1个单元格数据,并封装在info实体stuName属性上
        /*info.setStuName(r.getCell(0).getStringCellValue());*/
        info.setName(r.getCell(0).getStringCellValue());
        System.out.println(info.getName());
        info.setPhone(r.getCell(1).getStringCellValue());
        temp.add(info);
        }
        fileIn.close();    
        return temp;    
    }

ListExcle 是自定义的一个实体类,保存excle中的字段,需要哪些字段自定义那些字段(个人写法)。
2.控制成

public String fileupload(){
        JSONObject object = new JSONObject();
        String name=request.getParameter("filename");
        String filename="D:/"+name;
        try {
            File file = new File(filename);
            List<ListExcle> list=sendingRecordService.loadScoreInfo(filename);
            object.put("list", list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return toJsonData(object.toString());
    }

因为本人是本地的,所以无法获取到路径,只能通过前端提示,将文件放到固定的盘下,然后通过前端传过的文件名字重新绑定、
3.前端获取文件方法

<input type="file" value="请选择文件" id="myfile" style="float:left;" onchange="fileupload(this);" />
var myfile = document.getElementById('myfile');
    var nodes=myfile.files[0].name;

猜你喜欢

转载自blog.csdn.net/weixin_42932323/article/details/82500486
今日推荐