istt / campaign-manager

1 stars 0 forks source link

Display column names #3

Closed dinhtrung closed 6 years ago

dinhtrung commented 6 years ago

Add column names into data file impory

dinhtrung commented 6 years ago
setFileData(event, entity, field, isImage) {
        this.dataUtils.setFileData(event, entity, field, isImage);
        // Try to extract headers from current open file
        if (event && event.target.files && event.target.files[0]) {
            const file_1 = event.target.files[0];
            this.dataFileService.entity.name = file_1.name;
            if (file_1.type.match(/text/i)) {
                const fileReader = new FileReader();
                fileReader.onload = e => {
                    this.dataFileService.entity.dataCsvPreview = fileReader.result; // first line
                    // console.log('First line', this.dataFile.dataCsvPreview);
                    this.dataFileService.entity.dataCsvHeaders = fileReader.result
                        .split('\n')
                        .shift() // Extract first line
                        .split(/[;|,]/)
                        .map(f => f.replace(/[^\w]/g, '')); // Extract columns
                    // console.log('Headers', this.dataFile.dataCsvHeaders);
                    if (this.dataFileService.entity.dataCsvHeaders.length === 1) {
                        this.dataFileService.entity.dataCsvHeaders = ['msisdn'];
                    }
                    this.dataFileService.dataCsvHeaders = Object.assign([], this.dataFileService.entity.dataCsvHeaders);
                };
                // Read the file
                fileReader.readAsText(file_1.slice(0, 1024));
            } else {
                console.error('Cannot detect file type of the file...');
            }
        }
    }

This will read the first 1024 bytes from the input files to detect the headers, then set the header columns