React Open file dialog - javascript

I am trying to open a File Dialog Box with React, so that the user can select a folder and save the file in that particular folder, however I cannot manage to do that. My code looks like this at the moment:-
const exportToCSV = (csvData, fileName) => {
const ws = XLSX.utils.json_to_sheet(csvData);
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], {type: fileType});
FileSaver.saveAs(data, fileName + fileExtension);
}
const openDialogWindow = () => {
// Open dialog here and get the folder name
exportToCSV(csvData, (folderName + fileName))
};
return (
<button
id="btnExportToCSV"
onClick={(e) => openDialogWindow()}
>
Export Tasks To Excel
</button>
)
so in my openDialogWindow, I would like to have the option to open the dialog box, and let the user select a folder that I can then attach to the pre-defined fileName. This will give the user the option to save the file in his chosen directory.
Is this possible?
Thanks for your help and time!

Related

set download button disabled on Generating an excel file

I'm generating an excel sheet using exceljs and downloading it using file-saver packages
const saveFile = async (fileName: any, workbook: any) => {
protectSheet(validationSheet)
const xls64 = await workbook.xlsx.writeBuffer({ base64: true })
saveAs(
new Blob([xls64], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
fileName
)
}
the problem is when I trigger this function by clicking this button
<button ref={buttonRef} className="btn btn-info" onClick={() => {
saveFile(fileName, workbook)
}}>Download file</button>
it takes some time to protect and generate the excel file.
i need to disable the button during the protection and generation phase
then enable it back after downloading

PWA not sharing file with navigator.share, only dowload

This is my code
let f: any = XLSX.writeFile(wb, this.generarNombre(pedido.folio), {
bookType: 'xlsx',
type: 'array'
})
let data: Blob = new Blob([f], { type: EXCEL_TYPE })
let file = new File([data], this.generarNombre(pedido.folio), {
type: EXCEL_TYPE
})
let navigator = window.navigator as any
return new Promise((resolve, reject) => {
let data = {
files: [file],
title: this.generarNombre(pedido.folio),
text: pedido.folio
}
if (navigator.canShare(data))
navigator.share(data).then(result => resolve(result))
else reject('No soportado por el dispositivo')
})
}
My application is a PWA and it is installed successfully in android, the problem is that instead of sharing with the native option of android it only downloads the file. How can i solve this?
You can implement directly and check this out as in web.dev here
Or better use this pwa library, pwafire;
pwa.Share({
// Title of what to share
title: "Some title..",
// Text to share
text: "Some text...",
// List of files to share...
files: file_list
};)

Get input file path using NeutralinoJS

How do I get input file path using NeutralinoJS?
My Code:
<input type="file" id="inputFile">
const inputFilePath = document.getElementById('inputFile').files[0].path
console.log(inputFilePath)
I don't think browsers allow you to get file paths.
You could use the file picker API instead os.showDialogOpen(DialogOpenOptions):
https://neutralino.js.org/docs/api/os#osshowdialogopendialogopenoptions
<button onclick="onFileUpload()">
async onFileUpload () {
let response = await Neutralino.os.showDialogOpen({
title: 'Select a file'
})
console.log(`You've selected: ${response.selectedEntry}`)
}
Why do you need the path? If you need the content from the upload file you can get it via javascript filereader API and use the contents.
If you need the file for later use you can read the file via js filereader and then create and save a new file with filesystem.writeFile(WriteFileOptions) to your prefered location (maybe app internal temp path). Be sure the destination path exists. For that you can use filesystem.createDirectory(CreateDirectoryOptions).
Example with jQuery:
jQuery(document).on('change','#myUpload',function(){ //Click on file input
if(jQuery(this).val().length > 0){ //Check if a file was chosen
let input_file = this.files[0];
let file_name = input_file.name;
let fr = new FileReader();
fr.onload = function(e) {
fileCont = e.target.result;
//Do something with file content
saveMyFile(file_name, fileCont); //execute async function to save file
};
fr.readAsText(input_file);
}
});
async function saveMyFile(myFileName, myFileContent){
await Neutralino.filesystem.createDirectory({ path: './myDestPath' }).then(data => { console.log("Path created."); },() => { console.log("Path already exists."); }); //create path if it does not exist
//write the file:
await Neutralino.filesystem.writeFile({
fileName: './myDestPath/' + myFileName,
data: myFileContent
});
}
You can use the Neutralino.os API for showing the Open/Save File Dialogs.
This is A Example For Opening A File.
HTML:
<button type="button" id="inputFile">Open File</button>
JavaScript:
document.getElementById("inputFile").addEventListener("click", openFile);
async function openFile() {
let entries = await Neutralino.os.showOpenDialog('Save your diagram', {
filters: [
{name: 'Images', extensions: ['jpg', 'png']},
{name: 'All files', extensions: ['*']}
]
});
console.log('You have selected:', entries);
}

Downloaded xlsx file with fileSaver is invalid when opened

I have written function where I want to download an xlsx file via a service. Download also works so far. But when I open the file I get the error message file extension or file format is invalid. How can I solve the problem?
Code:
// Service
getDownloadPlan(): Observable<any> {
const url = `/download-plan?sales-plan=0&personnel-plan=0&investment-plan=0&loan-plan=0&material-cost-plan=0`;
return this.http.get(`${environment.baseUrl}` + url, { responseType: 'blob'});
}
// TS
downloadPlanBwa() {
this.planBwaService.getDownloadPlan().subscribe(response => {
const downloadFile: any = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
fileSaver.saveAs(downloadFile, 'Plan');
}, error => console.log('ERROR'),
() => console.log('SUCCESSFUL')
);
}
If i use the MIME-Type application/vnd.ms-excel;charset=utf-8 this is for the xls-format then it works.
What do I need to change in my code to successfully open xlsx files?

Excel file contains {"sharedString":0} instead of actual value

I am trying to read from a excel file, manipulate and create another excel file from it, i am using stream support for this. Most of it is working fine but i see resultant excel file containing {"sharedString":0} instead of actual values.
Below is my relevant code
let ws = fs.createWriteStream(fpath);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({stream: ws, useStyles: true, useSharedStrings: true});
const myworksheet = workbook.addWorksheet('sheet1');
const workbookReader = new ExcelJS.stream.xlsx.WorkbookReader(sheet.path, options);
workbookReader.read();
workbookReader.on('worksheet', worksheet => {
worksheet.on('row', row => {
myworksheet.addRow(row.values);
});
});
workbookReader.on('shared-strings', sharedString => {
console.log('not coming here');
});
workbookReader.on('end', async () => {
console.log('processing done...');
await workbook.commit();
});
Please see the attached file for your reference.
Any help on how to fix this will be really great, Thanks.
Once i created the WorkbookReader with below options
const options = {
sharedStrings: 'cache',
hyperlinks: 'cache',
worksheets: 'emit',
styles: 'cache',
};
it worked!

Categories

Resources