Data download functionality for API response Angular - node.js

I have an API response where I'm getting data as comma separated values and not as JSON objects. I need to export this data into CSV file. Can someone please suggest a method to do this?

You could parse your data to a JSON-object:
const apiData: string = 'value1,value2,value3';
const data: string[] = apiData.split(',');
And then you could use a combination of xlsx and fileSaver
Pseudocode:
const worksheet: xlsx.WorkSheet = xlsx.utils.json_to_sheet(data);
const workbook: xlsx.WorkBook = {
Sheets: { [worksheetName]: worksheet },
SheetNames: [worksheetName]
};
const buffer = xlsx.write(workbook, { 'csv', type: 'array' });
const blob = new Blob([buffer], { type: 'text/comma-separated-values' });
fileSaver.saveAs(blob, 'filename.csv');

Related

Google Gloud Vision API - Return Output as JSON Object rather than to a GCS file

I am utilising the Cloud Vision API "PDF to Text" function for a Node.js app. I have mostly stuck close to the GCP docs example, with a couple of tweaks here and there: https://cloud.google.com/vision/docs/pdf
All works fine, however I would like the contents of the file to be returned to me as a JSON object so I can pass it into another funciton, rather than its current behaviour of writing the contents to a JSON file and storing it on Cloud Storage.
Does anyone know how I need to structure the outputConfig object in order to achieve this?
async function detectPdfText(bucketName, fileName) {
// Imports the Google Cloud client libraries
const vision = require('#google-cloud/vision').v1;
// Creates a client
const client = new vision.ImageAnnotatorClient({
keyFilename: './APIKey.json'
});
// The directory to store the results
const outputPrefix = 'json_output'
const gcsSourceUri = `gs://${bucketName}/${fileName}`;
const gcsDestinationUri = `gs://${bucketName}/${outputPrefix}/`;
const inputConfig = {
// Supported mime_types are: 'application/pdf' and 'image/tiff'
mimeType: 'application/pdf',
gcsSource: {
uri: gcsSourceUri,
},
};
const outputConfig = {
gcsDestination: {
uri: gcsDestinationUri,
},
};
const features = [{type: 'DOCUMENT_TEXT_DETECTION'}];
const request = {
requests: [
{
inputConfig: inputConfig,
features: features,
outputConfig: outputConfig,
},
],
};
const [operation] = await client.asyncBatchAnnotateFiles(request);
const [filesResponse] = await operation.promise();
const destinationUri =
filesResponse.responses[0].outputConfig.gcsDestination.uri;
console.log(`Json output for file ${fileName} has been saved to: ${destinationUri}`);
}
module.exports = { detectPdfText };
You are using asyncBatchAnnotateFiles, which only writes the output to GCS: https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#outputconfig . There is no option to return the result of the LRO in the GetOperation call.
You could instead use batchAnnotateFiles and get the results synchronously, then convert to json.
If you have to use asyncBatchAnnotateFiles, then you would have to download the GCS file after the LRO finishes.

Angular how to read an excel file from an assets folder using typeScript

Ashamed to ask, but for resolving my problem I need to ask.
So, I have a problem with reading data from an excel file in my Angular project. The file is located in the assets folder.
I know how to get a file from the folder.
In app.component.ts inside ngOnInit I get a file:
ngOnInit() {
this.http.get('assets/dataTest.xlsx').subscribe((data: any) => {
console.log("get: " + data);
});
}
How I understand inside http.get I need to use code below:
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
console.log("READ " + e);
};
reader.readAsBinaryString(data);
But it does not work. I get an error:
ERROR TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.
Help me please with reading data from an excel file is located in the assets folder.
I suggest to use a library to parse the excel file.
See there an example of SheetJs:
/* <input type="file" (change)="onFileChange($event)" multiple="false" /> */
/* ... (within the component class definition) ... */
onFileChange(evt: any) {
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target);
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader();
reader.onload = (e: any) => {
/* read workbook */
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
/* grab first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
this.data = <AOA>(XLSX.utils.sheet_to_json(ws, {header: 1}));
};
reader.readAsBinaryString(target.files[0]);
}
i just solve the problem with this.
read() {
this.httpClient.get('assets/files/Report DTP.xls', { responseType: 'blob' })
.subscribe((data: any) => {
const reader: FileReader = new FileReader();
let dataJson1;
let dataJson2;
reader.onload = (e: any) => {
const bstr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
/* grab first sheet */
const wsname1: string = wb.SheetNames[1];
const ws1: XLSX.WorkSheet = wb.Sheets[wsname1];
/* grab second sheet */
const wsname2: string = wb.SheetNames[2];
const ws2: XLSX.WorkSheet = wb.Sheets[wsname2];
/* save data */
dataJson1 = XLSX.utils.sheet_to_json(ws1);
dataJson2 = XLSX.utils.sheet_to_json(ws2);
console.log(dataJson1);
};
reader.readAsBinaryString(data);
console.log(data);
});
}
I hope it helps you even though it's late :)

How to generate excel file using node.js?

Hi I am go for the generate excel file form the array but I am not getting successes. I am work using node.js and I am use npm package for generate excel file but I am not getting any data in excel file. excel is generate but not getting any type of data in my file. so any one know where is my mistake then please let me know how can fix it.
This is my array and query =>
var XLSX = require('xlsx');
var Array = [];
Array.push({
username: 'Carakc',
fullName: 'Crack',
followingCount: 2655,
followerCount: 466,
biography: 'I am new man'
},
{
username: 'mahi',
fullName: 'Fit',
followingCount: 3011,
followerCount: 385,
biography: 'hello everyone!'
})
app.get(prefix + '/GetFollowersInExcel', function (req, res, next) {
var ws = XLSX.utils.json_to_sheet(Array);
var wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Followres");
var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
res.end(wbout, 'binary');
}
});
}
});
})
This is my service code =>
GetFollowersInExcel: function (InstaId) {
return $http({
method: "GET",
url: ONURL + "GetFollowersInExcel",
responseType: "arraybuffer",
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).then(function (data, status, xhr) {
debugger;
if (data.data.byteLength > 0) {
var file = new Blob([data.data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
$('#getexcel').show();
var link = document.createElement('a');
link.href = fileURL;
link.download = "myfile.xlsx";
link.click();
URL.revokeObjectURL(file);
}
}, function (error) {
return error;
})
},
using this wave I am getting like this data in excel =>
I want like this data in excel file =>
I've tried your first code and I've found no errors, the resulting xlsx is perfect.
Peheraps I've found the problem: var Array is declared outside the app.get callback... Are you sure that your var Array can be correctly reached by XLSX.utils.json_to_sheet? it's in the same scope? or it's declared somewhere inaccessible?
try to declare it inside the callback and probably all will work well, and, if this is the case, you can use a class or a method to retrieve the var from outside ("how" depends on your code)
P.s. change the name of the var, is not a good habit overwrite the Array object ;)

Formatting rows in excel using sheetjs in angular2

I am using Sheetjs to write json content in the file. I am able to write into file and download. Most my report export intigrated with this an everything works.
But I have recently got new excel format which looks something like
I am not able to implement like this using sheetjs. I tried most of issue on GIT account and read about it ,but still nothing helped me.
Below is the generic code block for reference
public exportAsExcelFile(jsonint: any[], excelFileName: string,replaceMap:any,headerOrder: string[]): boolean {
var jsonData =this.replaceKeyInObjectArray(jsonint,replaceMap);
var orderedJSON = JSON.parse(JSON.stringify( jsonData, headerOrder, 10));
let worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(orderedJSON);
const workbook: XLSX.WorkBook = { Sheets: {'data': worksheet}, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook,{ bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
return true; }
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
})
FileSaver.saveAs(data, fileName + '-' + Util.getCurrDate("_") + EXCEL_EXTENSION); }
If someone know this help me out.Thanks in advance

writeFile not woking in exceljs

i am using exceljs and try to write value in a cell but it does not working. However workbook.xlsx.readFile(filename) is working but workbook.xlsx.writeFile(filename) won't.
Here is my code:-
var Excel = require('exceljs');
var fs = require('fs')
module.exports.summary = function(req, res, next) {
try {
var filename = process.cwd() + '/template/report/summary.xlsx';
var workbook = new Excel.Workbook();
workbook.xlsx.writeFile(filename)
.then(function() {
var worksheet = workbook.getWorksheet(1);
console.log('worksheet',worksheet);
var row = worksheet.getRow(5);
row.getCell('C').value = new Date();
row.commit();
worksheet.commit();
workbook.commit().then(function() {
console.log('xls file is written.');
});
res.json({ msg: done })
});
} catch (e) {
next(e);
}
}
Try this code, Hope this will help you
const excel = require('exceljs');
//Creating New Workbook
var workbook = new excel.Workbook();
//Creating Sheet for that particular WorkBook
var sheetName = 'Sheet1';
var sheet = workbook.addWorksheet(sheetName);
//Header must be in below format
sheet.columns = [{key:"name", header:"name"}, {key: "age", header: "age"}];
//Data must be look like below, key of data must be match to header.
var data = [{name:"Kalai", age: 24}, {name:"Vignesh", age:24}];
//adding each in sheet
for(i in data){
sheet.addRow(data[i]);
}
//Finally creating XLSX file
var fileName = "Sample.xlsx";
workbook.xlsx.writeFile(fileName).then(() => {
callback(null);
});
writeFile is no longer supported, so I suggest you to exchange it for "writeBuffer".
This code worked to me:
const buffer = workbook.xlsx.writeBuffer();
const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
let EXCEL_EXTENSION = '.xlsx';
const blob= new Blob([buffer], {type: fileType});
saveAs(blob, 'filename' + EXCEL_EXTENSION);
In my case i have name like "data2022/2023" the main problem is "/" when i remove the slash "data2020" its work. Dunno why cant use unicoden"/"

Resources