How to create csv or Excel file using javascript in Cordova android app - phonegap-plugins

I am trying to create android app using phoneGap. I have written code for creating csv file in javascript ,which works fine on browser,but its not working in mobile app created using cordova.Everything other than file creation works fine in cordova app.Pl. guide
I have used following permissions in manifest,
Code for creating csv file:-
var link = document.getElementById("dataLink");
var csv = "";
//we should have the same amount of name/cookie fields
var name = "testdata1";
var cookies = "testdata2",
csv = csv + ""+ name + "," + cookies + "\n";
console.log("csv-"+csv);
$("#dataLink").attr("href", 'data:Application/octet-stream,' + encodeURIComponent(csv))[0].click();

You will need to use the File Plugin of Crodova to write file to the file system as different Operating System have only certain directories accessible to the Application to read/write.
The code to create the file object and writing will look something like this
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir) {
console.log("got main dir", dir);
dir.getFile("myfile.csv", {
create: true
}, function(file) {
console.log("got the file", file);
logOb = file;
var csv = "";
//we should have the same amount of name/cookie fields
var name = "testdata1";
var cookies = "testdata2",
csv = csv + "" + name + "," + cookies + "\n";
console.log("csv-" + csv);
writeLog(csv);
});
});
function writeLog(str) {
if (!logOb) return;
logOb.createWriter(function(fileWriter) {
fileWriter.seek(fileWriter.length);
var blob = new Blob([str], {
type: 'text/plain'
});
fileWriter.write(blob);
console.log("ok, in theory i worked");
}, fail);
}
You can refer to this tutorial to better understand the process of file writing.

Related

How to read data from the downloaded excel file content from Google drive api in Dart/Flutter?

I am using google drive API to download an excel file in my Flutter app but I want to store the downloaded file content response in a File and then do some update operations using excel dart package, below is the given code from reading an xlsx file from a path location.
var file = "Path_to_pre_existing_Excel_File/excel_file.xlsx"; //here I want to store the response from drive api
var bytes = File(file).readAsBytesSync();
var excel = Excel.decodeBytes(bytes);
//Do some logic here
for (var table in excel.tables.keys) {
print(table); //sheet Name
print(excel.tables[table].maxCols);
print(excel.tables[table].maxRows);
for (var row in excel.tables[table].rows) {
print("$row");
}
}
//then saving the excel file
// updating the excel sheet to Drive
updateToDrive(excel,fileId);
I have created all the required auth functions, drive scopes and my download function looks like this :
Future<void> downloadFile() async{
String fileId = '1TOa4VKfZBHZe######WLA4M95nOWp';
final response = await driveApi.files.get(
fileId,
downloadOptions: drive.DownloadOptions.fullMedia
);
print(response);
}
This function is executing correctely and giving Media type response, but I could not able to read this response so that I could store it in a file.
Any help would be truly appreciated, Thanks
I changed my download function to this, as drive.files.get() was returning a Future Object so I changed it to return Future<Media?> by type casting.
String fileId = "19jF3lOVW563LU6m########jXVLNQ7poXY1Z";
drive.Media? response = (await driveApi.files.get(
fileId,
downloadOptions: drive.DownloadOptions.fullMedia
)) as drive.Media?;
Now response is a Media on which we can listen to the sream to store the response in a file.
To do that first we need to get the app directory by path_provider
final String path = (await getApplicationSupportDirectory()).path;
final String fileName = '$path/Output.xlsx';
File file = File(fileName);
Now we want to write the stream of response Stream<List> into our file object which I found from this link
List<int> dataStore = [];
await response!.stream.listen((data) {
print("DataReceived: ${data.length}");
dataStore.insertAll(dataStore.length, data);
}, onDone: () {
print("Task Done");
file.writeAsBytes(dataStore);
OpenFile.open(file.path);
print("File saved at ${file.path}");
}, onError: (error) {
print("Some Error");
});
Now we can do whatever we want to make changes through excel package.

Is there a way to convert an excel file to a google sheet file with Google Apps scripts?

I am working on trying to convert files that I am copying to a shared drive from my email. The files are saved in xlsx and I lose information if I try to download them from the source as .csv files.
function convertExceltoGoogleSpreadsheet(fileName) {
try {
fileName = "JNJ Defects Last Shift.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var folderId = "0AEZiKNnbsme8Uk9PVA";
var blob = excelFile.getBlob();
//var resource = {
//title: excelFile.getName(),
//mimeType: MimeType.GOOGLE_SHEETS,
//parents: [{id: folderId}],
//};
blob.setContentType("application/vnd.google-apps.spreadsheet").setName("JNJ Defects Last Shift 22 Jun 20");
DriveApp.createFile(blob);
//Drive.Files.insert(resource, blob);
} catch (f) {
Logger.log(f.toString());
}
}
When I run it I get this error message
[20-06-23 07:06:08:638 CDT] Exception: Invalid argument: file.contentType.
I have tried a couple of variations of the contentType but did not manage to convert to sheets.
How can I do?
Answer:
You can do this with the Advanced Drive Service.
More Information:
In order to do the conversion, you need to specify specifically that you wish to convert the file, though as this will default to a Google Sheet format, you do not need to manually specify the MimeType.
Code:
function convertExceltoGoogleSpreadsheet(fileName) {
fileName = "JNJ Defects Last Shift.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var folderId = "0AEZiKNnbsme8Uk9PVA";
var blob = excelFile.getBlob();
var file = {
title: "JNJ Defects Last Shift 22 Jun 20",
parents: [
{
"kind": "drive#parentReference",
"id": folderId
}
]
};
file = Drive.Files.insert(file, blob, {
convert: true
});
}

Transfer data in Excel attachment, in Outlook or Gmail, to Google sheet

I daily receive an email in Outlook with an Excel sheet attached.
I am working with dashboard/templates in Google data studio, and Google sheets. To make this work smoothly, I need to transfer the data from the Excel sheet to my Google sheet automatically. Is this possible?
My first thought was to send the attached Excel sheets to my gmail instead, because from here I could write a script that gets the data from the gmail. This was more complicated than I thought.
Maybe a VBA code to transfer the attached Excel file to google-drive, and then from there I could update my Google sheet? Is this possible?
Note: I am not experienced enough to write VBA/APP script from scratch.
Q: The OP asks: is it possible to transfer an Excel spreadsheet, received as an Outlook attachment, to google-drive, and then update it to a Google Sheet format?
A: Yes.
Q: What are the discrete steps required to satisfy the OP's objective?
A:
1 - Write a macro in Outlook to automatically forward the email and Excel attachment to the OP's GMail account; specifically to the account used to log into Google Sheets. For the purposes of this answer this aspect, though fairly straightforward, this is treated as off topic.
2 - Create a folder (or folder/subfolder) in Google Drive where the Excel spreadsheet can be saved. This could be done manually or by script. "Manually" is easier, "by script" is more fun and offers more flexibility.
3 - Run a Google script to access the OP's Gmail account, identify Excel attachments (say, files ending with 'xls', 'xlsx', 'xlsm' - other variations can be added), and save the Excel file to the Google Drive folder. Attach a "label" to each relevant email so that only new unprocessed messages are processed.
4 - Run a Google script to access the Google Drive folder/subfolder and convert the Excel spreadsheet to a Google Sheet.
As noted in comments, this topic has been raised, in one form or another, many times before: Is there any google API which could save gmail message attachments to google drive? and Convert all xls files available in a folder into “Google Doc Spreadsheets”? are two good examples. Google search will reveal many other topics - on StackOverflow and other sources.
However Google services (Docs, scripts, APIs, etc) are being constantly enhanced. One of the by-products of this development is that some methods are discontinued and this can render a previously correct answer to become out-of-date.
Unfortunately this is the case with the excellent GmailToDrive() function supplied in the Jan 2018 answer to Is there any google API which could save gmail message attachments to google drive?. Google Advanced Drive Service and Drive API changed during 2018 and that excellent answer now falls at the last hurdle.
The following code is supplied in order to provide an update to February 2019.
The basis of this answer is the GmailToDrive() function provided by Mr.Rebot, but modified for Excel files.
Trigger
The code should be set as a time-driven, Installable Trigger. The frequency will vary from case to case. The OP can make their own assessment. There are other sources that are available to explain this.
Drive API
The OP must activate the Drive API (Advanced Services as well as the Google Cloud Platform API Dashboard). For the sake of clarity, a brief outline of the steps is at the end of this answer.
Code
// GLOBALS
// Array of file extension which you would like to extract to Drive
var fileTypesToExtract = ['xls', 'xlsx', 'xlsm'];
//Name of the folders in google drive in which files will be put
var homeFolder = "009-StackExchange"; // a folder branching from the root
var ExcelFolderName = "010-GmailToDrive"; // sub folder of "homeFolder"
//Name of the label which will be applied after processing the mail message
var emaillabelName = 'GmailToDrive';
function so54755021()
// an adaptation of function GmailToDrive()
{
//build query to search emails
var query = '';
// loop through the filestoextract and add to query
for (var i in fileTypesToExtract) {
query += (query == '' ? ('filename:' + fileTypesToExtract[i]) : (' OR filename:' + fileTypesToExtract[i]));
}
//Logger.log("DEBUG: #01 the query is: " + query); //DEBUG
query = 'in:inbox has:nouserlabels ' + query;
//Logger.log("DEBUG: #02 the query is: " + query); //DEBUG
var threads = GmailApp.search(query);
//Logger.log("DEBUG: threads = " + threads + "; threads length = " + threads.length); //DEBUG
var label = getGmailLabel_(emaillabelName);
//Logger.log("DEBUG: label = " + label); //DEBUG (GmailToDrive)
var parentFolder;
if (threads.length > 0) {
//Logger.log("DEBUG: threads length is more than zero");//DEBUG
//Logger.log("DEBUG: folder name = " + folderName); //DEBUG
//parentFolder = getFolder_(folderName); // subroutine
// build sub-folder if necessary
createDriveFolder(homeFolder, ExcelFolderName);
parentFolder = homeFolder;
}
for (var i in threads) {
var mesgs = threads[i].getMessages();
for (var j in mesgs) {
//get attachments
var attachments = mesgs[j].getAttachments();
for (var k in attachments) {
var attachment = attachments[k];
//Logger.log("DEBUG: attachment: " + attachment);//DEBUG
var isExcelType = checkIfExcel_(attachment);
//Logger.log("DEBUG: isExceltype = " + isExcelType);//DEBUG
if (!isExcelType) continue;
// Copy the Blob
var attachmentBlob = attachment.copyBlob();
//Logger.log("DEBUG: attachmentblob = " + attachmentBlob);//DEBUG
var ExcelFolderObject = DriveApp.getFoldersByName(ExcelFolderName).next();
//Create the Excel file in Google Drive
var file = ExcelFolderObject.createFile(attachmentBlob);
// get the file name and ID
var fileid = file.getId();
var filename = file.getName();
// Logger.log("DEBUG: file = " + file + ", and ID = " + fileid + ", and file name: " + filename);//DEBUG
var fileType = file.getMimeType()
// Logger.log("DEBUG: the MIME type is " + fileType);//DEBUG
// copy the Blob again in preparation for conversion
var xBlob = file.getBlob();
// get the folder ID to copy the file
var folderId = DriveApp.getFoldersByName(ExcelFolderName).next().getId();
// set parameters for the new file
var newFile = {
title: filename + '_converted',
key: fileid,
parents: [{
"id": folderId
}]
}
// convert the file
var convfile = Drive.Files.insert(newFile, xBlob, {
convert: true
});
// Logger.log("DEBUG: the converted file is " + convfile);//DEBUG
}
}
// Add the label to the Gmail item
threads[i].addLabel(label);
}
}
// If necessary, create the label in GMail
function getGmailLabel_(name) {
var label = GmailApp.getUserLabelByName(name);
if (label == null) {
label = GmailApp.createLabel(name);
}
return label;
}
function createDriveFolder(baseFolder, folderName) {
var baseFolderObject = DriveApp.getFoldersByName(baseFolder).next();
//Logger.log("DEBUG: basefolderobject = " + baseFolderObject);//DEBUG
var folders = DriveApp.getFoldersByName(baseFolder).next().getFolders();
//Logger.log("DEBUG: folders: "+folders);//DEBUG
// set variable to detect a match
var foldermatch = 0;
//Loop through folders
while (folders.hasNext()) {
var folder = folders.next();
//Logger.log(DEBUG: folder.getName());//DEBUG
// If the folder name matches
if (folder.getName() == folderName) {
// update the match variable
foldermatch = 1;
// Logger.log("DEBUG: there's a match/folder exists: " + folder.getName());//DEBUG
}
}
// Do something is there is a match
if (foldermatch != 0) {
//Logger.log("DEBUG: There was a match so do NOTHING");//DEBUG
} else {
// Logger.log("DEBUG: There was no match so create the folder"); //DEBUG
baseFolderObject.createFolder(folderName);
}
// The folder already existed, or it has been created. Either way, our work is done.
return;
}
// this function will check for filextension type.
// and return boolean
function checkIfExcel_(attachment) {
var fileName = attachment.getName();
var temp = fileName.split('.');
var fileExtension = temp[temp.length - 1].toLowerCase();
if (fileTypesToExtract.indexOf(fileExtension) != -1) return true;
else return false;
}
Enable the Drive Api
1 - From the Script Editor, select Resources > Advanced Google Services; select Drive API and slide the switch to On.
2 - Click the link to the "Google Cloud Platform API Dashboard"
3 - The Google Cloud Platform - APIs and Services screen opens in a new window.
Click the link to Enable APIs and Services
4 - Search for "drive", and then click the option for Drive API.
5 - Click the "Enable" button for the Drive API
6 - The system will display the Drive API details; note the Drive API is enabled. Then just close this window.
7 - Click OK on the "Advances Google Services" screen (which has remained open all this time).
You're ready to run the script.

Converting Microsoft Office docs in Google Drive to analog Google Docs files

I'm trying to convert all Office files (ex. Word docs, Excel spreadsheets, PowerPoint presentations, etc.) in a folder on my Google Drive into their google doc equivalents.
I'm using the Advanced Drive Service in Google Apps Script to perform this task.
My implementation is below:
function convert() {
var targetFolder_1 = DriveApp.getFoldersByName('Office Folder');
var targetFolder = targetFolder_1.next();
var folderGoogify_1 = DriveApp.getFoldersByName('Empty Folder');
var folderGoogify = folderGoogify_1.next();
var counter = 0;
var files = targetFolder.getFiles();
var folderID = targetFolder.getId();
while (files.hasNext()) {
var nextFile = files.next();
var blob = nextFile.getBlob();
var fileName = nextFile.getName();
var file = {
title: fileName,
"parents": [{
"kind": "drive#parentReference",
"id": folderID
}]
};
file = Drive.Files.insert(file, blob, {
convert: true
});
counter++;
folderGoogify.addFile(file);
}
}
However, at the last line I receive the following error:
Cannot convert [object Object] to File.
How can I adapt my code so that the converted file is recognized as a File, and not an Object?
Modification points :
The response of Drive.Files.insert() is JSON data. This is not file. So such error occurs. When you see the file using Logger.log(file), you can see the JSON data.
In this case, "parents": [{id: folderid}] is folderGoogify.
You can directly create the converted files to the specific folder using Drive API. It is not necessary to use addFile().
The modified script reflected them is as follows.
Modified script :
function convert() {
var targetFolder_1 = DriveApp.getFoldersByName('Office Folder');
var targetFolder = targetFolder_1.next();
var folderGoogify_1 = DriveApp.getFoldersByName('Empty Folder');
var folderGoogify = folderGoogify_1.next();
var counter = 0;
var files = targetFolder.getFiles();
while (files.hasNext()) {
var nextFile = files.next();
var blob = nextFile.getBlob();
var fileName = nextFile.getName();
var file = {
title: fileName,
"parents": [{"id": folderGoogify.getId()}],
"kind": "drive#parentReference",
};
counter++;
file = Drive.Files.insert(file, blob, {convert: true});
}
}
If I misunderstand your question, I'm sorry.
You need to create the document with something like
SpreadsheetApp.create("Example File Name")
This will create the spreadsheet . You are trying to add info to a object, not a file, this will add it to a file.
Google Sheets Script Error - Cannot convert [object Object] to Spreadsheet

Windows 10 App - File downloading

I am working with Windows 10 universal app and i want to download a file in that. The file link to Sharepoint server. I have passed token in headr to a web service and then service returned byte array to my WinJS.
Now i want to save the file, how can i do this? I tried several code samples but not working.
var folder = Windows.Storage.ApplicationData.current.localFolder;
folder.createFileAsync("document.docx", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, result.response);
}).then(function () {
//saved
});
I am using above code and it is creating new file but no content is placed there. Please suggest what to do.
You never open the file for WriteAccess. I have included code from my working app. First do this command
StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);
then do this:
// Get the file.
var ageFile = await local.OpenStreamForWriteAsync("Age.txt",CreationCollisionOption.OpenIfExists);
// Read the data.
using (StreamWriter streamWriter = new StreamWriter(ageFile))
{
streamWriter.WriteLine(cmbAgeGroup.SelectedIndex + ";" + DateTime.Now);
streamWriter.Flush();
}
ageFile.Dispose();

Resources