I am new to ionic and when I try to export excel nothing is happening on my device but it works on my browser.
here is my code.
scannedResult: any[] = [];
excel: any;
contentvisibility = 'show';
displayedColumns = ['firstname', 'lastname', 'company', 'email'];
base64result: any;
mstorage: Storage | null = null;
key = 'key_' + Date.now().toString();
private fileTransfer: FileTransferObject;
constructor(private barcodeScanner: BarcodeScanner,
private toastr: ToastrService, private storage: Storage, private plt: Platform,
) {
this.storage.create();
this.storage.get('item').then((res) => {
if (res) {
this.scannedResult = res;
}
});
}
async ngOnInit() {
await this.storage.create();
}
startScan() {
this.barcodeScanner.scan().then(barcodeData => {
console.log('Barcode data', barcodeData);
this.scannedResult.push(JSON.parse(barcodeData.text));
this.storage.set('item', this.scannedResult)
.then(
() => {
this.toastr.success('Item Stored Success');
},
error => console.error('Error storing item', error)
);
return barcodeData;
}).catch(err => {
console.log('Error', err);
});
}
async createExcel() {
const ws = XLSX.utils.json_to_sheet(this.scannedResult);
// eslint-disable-next-line
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const buffer = XLSX.write(wb, {
bookType: 'xlsx',
type: 'array'
});
alert(buffer);
const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetxml.sheet';
const blob: Blob = new Blob([buffer], { type: fileType });
this.base64result = this.convertFile(blob);
this.saveToPhone(this.base64result);
}
saveToPhone(buffer: any) {
//for mobile native save
Filesystem.writeFile({
path: "Visitor_file10.xlsx",
data: buffer,
directory: Directory.Documents,
});
//for browser save
const downloadLink = document.createElement('a');
const fileName1 = 'sample.xlsx';
downloadLink.href = this.linkSource;
downloadLink.download = fileName1;
downloadLink.click();
const currentDate = new Date().toLocaleString().replace(/[,:\s\/]/g, '-');
const name = `myFile-${currentDate}.xlsx`;
console.log(name);
const readFilePath = () => {
const contents = Filesystem.readFile({
path: name
});
console.log('data:', contents);
};
console.log('data:', readFilePath);
console.log("this is sit");
console.log('this is siaat');
}
// convertBlobtoBase64 = (blob: Blob) => new Promise((resolve, reject)=>{
// const reader = new FileReader();
// reader.onerror = reject;
// reader.onload = () => {
// resolve(reader.result);
// };
// reader.readAsDataURL(blob);
// });
convertFile(file : Blob) : Observable<string> {
const result = new ReplaySubject<string>(1);
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (event) => result.next(btoa(event.target.result.toString()));
return result;
}
}