I am creating an application in React and .NET Core API. I have created mine grid (not using any npm package for this).
There is functionality required to export grid data to pdf, excel and csv format. How can i achieve this without any npm package or library?
I will get data(in List) form server (.NET core API) on download click button.
I have tried some npm packages like react-csv, downloadjs but they are not working as expected.
Mine data in array of objects format:
[{firstColumn: "1", secondCoulmn: "4", thirdColumn: "test"},
 {firstColumn: "2", secondCoulmn: "3", thirdColumn: "test2"}]
When i am passing this data in downloadjs then excel file having [Object object] content and PDF file generated is corrupted.
For react-csv it is generating unknown file like b0d7cfd9-f4ca-4792-bfad-2b3198c63a33
Assuming data is grid you want to export
In case of csv :
const csvContent = data.map(d=>d.join(",")).join("\n")
const element = document.createElement('a');
element.setAttribute(
  'href',
  `data:text/plain;charset=utf-8, ${encodeURIComponent(csvContent)}`,
);
element.setAttribute('download', `${fileName}.csv`);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element); 
if data is complex you may use PapaParse
const csvContent = Papa.unparse(data);
In case of Xls :
use SheetJS library
example :
const sheet = XLSX.utils.json_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet 1');
XLSX.writeFile(workbook, `${fileName}.xls`);
In case of pdf:
you need to create the html of grid
then you can use the jsPDF library:
Generate pdf from HTML in div using Javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With