• angular8表格文件上传并渲染到页面(上传文本与表格,表格有两种写法--第一种写法)


     表格方法一:利用js将上传的表格 转换成json数据(可转换所有的sheet)

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script>
    </head>
    
    <body>
    <input type="file" onchange="sendfile(this)" />
    <div id="demo"></div>
    <script>
        var zzexcel;
        function sendfile(obj) {
            if(!obj.files) {
                return;
            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.readAsBinaryString(f);
            reader.onload = function(e) {
                var data = e.target.result;
                zzexcel = XLSX.read(data, {
                    type: 'binary'
                });
                for(var i=0;i<zzexcel.SheetNames.length;i++){
                    document.getElementById("demo").innerHTML +=zzexcel.SheetNames[i]+"="+JSON.stringify(XLSX.utils.sheet_to_json(zzexcel.Sheets[zzexcel.SheetNames[i]]))+"<br/>";
                }
            }
        }
    </script>
    </body>
    </html>

    只操作当页

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="http://oss.sheetjs.com/js-xlsx/xlsx.full.min.js"></script>
    </head>
    <body>
    <input type="file"onchange="importf(this)" />
    <div id="demo"></div>
    <script>
        /*
         FileReader共有4种读取方法:
         1.readAsArrayBuffer(file):将文件读取为ArrayBuffer。
         2.readAsBinaryString(file):将文件读取为二进制字符串
         3.readAsDataURL(file):将文件读取为Data URL
         4.readAsText(file, [encoding]):将文件读取为文本,encoding缺省值为'UTF-8'
         */
        var wb;//读取完成的数据
        var rABS = false; //是否将文件读取为二进制字符串
    
    
        function importf(obj) {//导入
            if(!obj.files) {
                return;
            }
            var f = obj.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var data = e.target.result;
                if(rABS) {
                    wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                        type: 'base64'
                    });
                } else {
                    wb = XLSX.read(data, {
                        type: 'binary'
                    });
                }
                //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                //wb.Sheets[Sheet名]获取第一个Sheet的数据
                document.getElementById("demo").innerHTML= JSON.stringify( XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) );
            };
            if(rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        }
    
    
        function fixdata(data) { //文件流转BinaryString
            var o = "",
                l = 0,
                w = 10240;
            for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
            return o;
        }
    </script>
    </body>
    
    
    </html>

    文本上传

    <nz-button-group [nzSize]="size" style="padding:20px;display:flex">
      <button nz-button (click)="scrollToIndex(200)">下拉</button>
      <div style="text-align: center;display:inline-block;overflow: hidden;">
        <span class=" fileinput-button">
            <span nz-button nzType="primary" style="display:inline-block;line-height: 30px">点击上传excel文件</span>
            <!-- <input type="file" (change)="myUploadexcel($event)"/> -->
            <input type="file" (change)="readExcel($event)"/>
        </span>
    </div>
    <div style="text-align: center;display:inline-block;overflow: hidden;">
      <span class=" fileinput-button">
          <span nz-button nzType="primary" style="display:inline-block;line-height: 30px">点击上传txt文件</span>
          <input type="file" (change)="myUploadtxt($event)">
      </span>
    </div>
    </nz-button-group>
    <div class="myitem-one-list">
        <st #st [data]="data" [columns]="columns" [page]="page" virtualScroll [scroll]="{ x: '500px', y: '240px' }"></st>
    </div>
    import { Component, OnInit , ViewChild, OnDestroy, AfterViewInit } from '@angular/core';
    import { STColumn, STPage, STComponent } from '@delon/abc';
    import { Subject } from 'rxjs';
    import { takeUntil } from 'rxjs/operators';
    import * as XLSX from 'xlsx';
    import { NzMessageService, NzNotificationService } from 'ng-zorro-antd';
    @Component({
      selector: 'app-item-one',
      templateUrl: './item-one.component.html',
      styleUrls: ['./item-one.component.less']
    })
    export class ItemOneComponent implements AfterViewInit, OnDestroy {
      private mylist;
      private destroy$ = new Subject();
      @ViewChild('st', { static: false }) st: STComponent;
      constructor(private msg:NzMessageService) {}
    
      page: STPage = {
        front: false,
        show: false,
      };
      data: any[] = Array(2000)
        .fill({})
        .map((_item: any, idx: number) => {
          return {
            id: idx + 1,
            mysn: ~~(Math.random() * 100),
          };
        });
      columns: STColumn[] = [
        { title: '编号', index: 'id',  '150px' },
        { title: '货号', index: 'mysn',  '250px' }
      ];
    
      // 上传表格1
      myUploadexcel(e){
        console.log('excel');
        console.log(e);
      }
      // 上传表格2
      // 上传文本1
      myUploadtxt(e){
        console.log('txt');
        console.log(e);
        let fileReader = new FileReader();
        fileReader.onload=()=>{
          console.log(fileReader.result);
          this.data=fileReader.result.toString().split(/[s]+/gm).map((item,idx)=>{
            return {
              id: idx + 1,
              mysn: item,
            };
          });
        }
        // fileReader.readAsText(e.target.files[0], 'utf-8')
        fileReader.readAsText(e.target.files[0])
      }
      // 上传文本2
      // 上传表格1
      readExcel(e) {//表格导入
        const files = e.target.files;
        console.log(files);
        if(files.length<=0){//如果没有文件名
        return false;
        }else if(!/.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
        this.msg.error('上传格式不正确,请上传xls或者xlsx格式');
        return false;
        }
     
        const fileReader = new FileReader();
        fileReader.onload = (ev:any) => {
        try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
            type: 'binary'
            });
            const wsname = workbook.SheetNames[0];//取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
            console.log(ws);
            this.mylist = [];//清空接收数据
            //编辑数据
            for(var i= 0;i<ws.length;i++){
            this.mylist.push(ws[i]);
            }
            // 此时得到的是一个内容是对象的数组需要处理
            this.mylist.map((item)=>{
              item.
            })
            console.log(this.mylist)
     
        } catch (e) {
          console.log('出错了')
            return false;
        }
        };
        fileReader.readAsBinaryString(files[0]);
    }
      // 上传表格2
      scrollToIndex(index: number): void {
        this.st.cdkVirtualScrollViewport.scrollToIndex(index);
      }
    
      ngAfterViewInit(): void {
        this.st.cdkVirtualScrollViewport.scrolledIndexChange.pipe(takeUntil(this.destroy$)).subscribe(data => {
          console.log('scroll index to', data);
        });
      }
    
      ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
      }
    }

  • 相关阅读:
    游标第一次应用
    HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法
    npoi导出excel(模板)插入图片,文本只读,不可以修改
    npoi导出excel(模板)
    iis7 发布mvc 遇到的HTTP错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容
    如何成为一个糟糕的程序员
    Mutiselect下拉复选框(保存和设置默认选中项)
    Android UI 绘制过程浅析(三)layout过程
    Android UI 绘制过程浅析(二)onMeasure过程
    [EventBus源码解析] 订阅者处理消息的四种ThreadMode
  • 原文地址:https://www.cnblogs.com/sugartang/p/11461737.html
Copyright © 2020-2023  润新知