Google Apps Script close UI App after execution - google-apps-script

I have a script that imports data from a csv file after inserting the name of the file via a UI. It all works 100%, the file is located and the data is imported as expected. However, the app does not close and the pop-up UI remains active on the screen.
My script is as follows:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{name: "Import Employee Base Data", functionName: "importFromBaseCSV"},
];
ss.addMenu("User Functions", menuEntries);
}
//IMPORT BASE DATA FROM CSV
function importFromBaseCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var importBaseDataApp = UiApp.createApplication().setTitle('Import BASE Data').setHeight(120).setWidth(350);
var importBaseDataGrid = importBaseDataApp.createGrid(3, 2);
importBaseDataGrid.setWidget(0, 0, importBaseDataApp.createLabel('Enter the File Date: '));
importBaseDataGrid.setWidget(0, 1, importBaseDataApp.createTextBox().setName('baseDataFilename').setFocus(true).setWidth(150));
importBaseDataGrid.setWidget(1, 0, importBaseDataApp.createLabel('e.g. 23092013'));
importBaseDataGrid.setWidget(2, 0, importBaseDataApp.createLabel(''));
var importBaseDataPanel = importBaseDataApp.createVerticalPanel();
importBaseDataPanel.add(importBaseDataGrid);
var importButton = importBaseDataApp.createButton('Import');
var importHandler = importBaseDataApp.createServerHandler('importBaseData');
importHandler.addCallbackElement(importBaseDataGrid);
importButton.addClickHandler(importHandler);
importBaseDataPanel.add(importButton);
importBaseDataApp.add(importBaseDataPanel);
ss.show(importBaseDataApp);
}
function importBaseData(e){
var fileName = "C BS BASE " + e.parameter.baseDataFilename + ".csv";
var files = DocsList.getFiles();
var csvFile = "";
for (var i = 0; i < files.length; i++) {
if (files[i].getName() == fileName) {
csvFile = files[i].getContentAsString();
break;
}
}
var csvData = CSVToArray(csvFile, ",");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Imported Base Data");
for (var i = 0; i < csvData.length; i++) {
sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
}
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
SpreadsheetApp.getActiveSpreadsheet().toast("...Completed", "Import Employee Base Data:", 3);
// Return the parsed data.
return( arrData );
var importBaseDataApp = UiApp.getActiveApplication();
importBaseDataApp.close();
return importBaseDataApp;
}
Can anyone help?

I just looked at it quickly, but try this. I moved the "Toast" and "Close" into the function that is called by the clickHandler. You want to control the Ui's in their calling function, its much smoother. Sometimes you might get lucky and they close or update calling them in another called function.
function importBaseData(e){
var fileName = "C BS BASE " + e.parameter.baseDataFilename + ".csv";
var files = DocsList.getFiles();
var csvFile = "";
for (var i = 0; i < files.length; i++) {
if (files[i].getName() == fileName) {
csvFile = files[i].getContentAsString();
break;
}
}
var csvData = CSVToArray(csvFile, ",");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Imported Base Data");
for (var i = 0; i < csvData.length; i++) {
sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
SpreadsheetApp.getActiveSpreadsheet().toast("...Completed", "Import Employee Base Data:", 3);
var importBaseDataApp = UiApp.getActiveApplication();
importBaseDataApp.close();
return importBaseDataApp;
}
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}

Related

Is there a way to stop my google script from wrapping text into a new cell? [duplicate]

I've pieced together this code from various google searches that will pull an e-mail's CSV attachment if the e-mail has a specific label.
function importCSVFromGmail() {
//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Monthly_Detail_Instantis");
//parses content of csv to array
var dataString = attachment.getDataAsString();
var escapedString = dataString.replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r\n(?:\\[\s\S][^'\\]\r\n)*')/g, '\\r\\n');
var csvData = Utilities.parseCsv(escapedString);
// Remember to clear the content of the sheet before importing new data
sh.clearContents().clearFormats();
//pastes array to sheet
sh.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
//marks the Gmail message as read and unstars it (Filter sets a star)
message.markRead();
message.unstar();
}
The script runs fine, however I am running into issues with cells that had values with commas or quotes. For example, if a cell has the following:
1,000,000
or
Google "Apps" Script
It will return to following, respectively.
\r\n
\r\n\r\n\r\n
I'm certain it has to do with the Regex used, however I am not certain how to adjust for the above. Any help with this would be greatly appreciated.
I was able to use the original code (used in question) and replace the escaping and Utilities.parseCsv with code from this link. This will properly import CSVs even if cells include quotes and commas:
https://productforums.google.com/forum/#!topic/docs/nhXjrl8JIek
Here is my final code:
function importCSVFromGmail() {
//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Monthly_Detail_Instantis");
//parses content of csv to array
var dataString = attachment.getDataAsString();
var csvData = CSVToArray(dataString);
// Remember to clear the content of the sheet before importing new data
sh.clearContents().clearFormats();
//pastes array to sheet
var lastRowValue = sh.getLastRow();
for (var i = 0; i < csvData.length; i++) {
sh.getRange(i+lastRowValue+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
}
//marks the Gmail message as read and unstars it (Filter sets a star)
message.markRead();
message.unstar();
}
//The code formats the code so it can be entered into the Google Script
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}

Importing csv file to google sheets using script

i am faced with the below problem. I am going to be presented with a .csv file that will contain the following fields:
ItemID Date Source name Title URL Created ItemSourceType
However i won't need all of the fields but i will need to import this into a pre-defined google sheets template, which looks like the below:
Date Writer Status Geog/Area/Product Source Title Note
Again not all of the columns will need to be populated, and so the final solution should look like this.
Date Writer Status Geog/Area/Product Source Title Note
Today() NULL NULL Null Site Title-(hyperlinked with URL) Null
i have put together the following code - some of this has been testing and trying to split out a CSV, and i've not yet attempted to add the hyperlinked field.
function addData() {
var fSource = DriveApp.getFolderById('138ZRbesgDkKHOROm4izD22oaXoanvsyJ'); // reports_folder_id = id of folder where csv reports are saved
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 12; // First row of data to process
var numRows = 2; // Number of rows to process
var fSource = DriveApp.getFolderById('138ZRbesgDkKHOROm4izD22oaXoanvsyJ'); // reports_folder_id = id of folder where csv reports are saved
var fi = fSource.getFilesByName('data.csv'); // latest report file
var ss = SpreadsheetApp.openById('1wBawJzQ3eAhyjCuetAFg7uUUrum6CDImBcVcxaZ9j84'); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data
if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv);
for ( var i=1, lenCsv=csvData.length; i<lenCsv; i++ ) {
sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
}
function CSVToArray( strData, strDelimiter ) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
};
// Fetch the range of cells A2:G3
var dataRange = sheet.getRange(startRow, 1, numRows,8)//sheet.getRange(startRow, 1, numRows, 8)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var ItemID = row[0]
var Date = row[1]
var SourceName = row[2]
var Title = row[3]
var URL = row[4]
var Created = row[5]
var ItemSourceType = row[6]
sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
var correctFormat = ItemID + ", " + Date + ", " + SourceName + ", " + Title + ", " + URL + ", " + Created + ", " + ItemSourceType;
Logger.log(correctFormat)
}
If anyone is able to help point me in the right direction it would be greatly appreciated.
The part of this that i am struggling with is using the Array to populate the spreadsheet with the fields in the correct order, I have put the array below.
function CSVToArray( strData, strDelimiter ) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
};
It seems like this site (https://ctrlq.org/code/20279-import-csv-into-google-spreadsheet) does include several ways to import a CSV into a google spreadsheet.
For instance for importing from google drive you can do:
function importCSVFromGoogleDrive() {
var file = DriveApp.getFilesByName("data.csv").next();
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
After that you will need to filter the data you want, but i guess it is easier to do that once you have imported the data from the csv.

Google Apps Script Gmail CSV Import to Sheet Error

I've pieced together this code from various google searches that will pull an e-mail's CSV attachment if the e-mail has a specific label.
function importCSVFromGmail() {
//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Monthly_Detail_Instantis");
//parses content of csv to array
var dataString = attachment.getDataAsString();
var escapedString = dataString.replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r\n(?:\\[\s\S][^'\\]\r\n)*')/g, '\\r\\n');
var csvData = Utilities.parseCsv(escapedString);
// Remember to clear the content of the sheet before importing new data
sh.clearContents().clearFormats();
//pastes array to sheet
sh.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
}
//marks the Gmail message as read and unstars it (Filter sets a star)
message.markRead();
message.unstar();
}
The script runs fine, however I am running into issues with cells that had values with commas or quotes. For example, if a cell has the following:
1,000,000
or
Google "Apps" Script
It will return to following, respectively.
\r\n
\r\n\r\n\r\n
I'm certain it has to do with the Regex used, however I am not certain how to adjust for the above. Any help with this would be greatly appreciated.
I was able to use the original code (used in question) and replace the escaping and Utilities.parseCsv with code from this link. This will properly import CSVs even if cells include quotes and commas:
https://productforums.google.com/forum/#!topic/docs/nhXjrl8JIek
Here is my final code:
function importCSVFromGmail() {
//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
// Is the attachment a CSV file
if (attachment.getContentType() === "text/csv") {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName("Monthly_Detail_Instantis");
//parses content of csv to array
var dataString = attachment.getDataAsString();
var csvData = CSVToArray(dataString);
// Remember to clear the content of the sheet before importing new data
sh.clearContents().clearFormats();
//pastes array to sheet
var lastRowValue = sh.getLastRow();
for (var i = 0; i < csvData.length; i++) {
sh.getRange(i+lastRowValue+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
}
}
//marks the Gmail message as read and unstars it (Filter sets a star)
message.markRead();
message.unstar();
}
//The code formats the code so it can be entered into the Google Script
function CSVToArray( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}

Import data from a single column of CSV file in Google Apps Script

I'm using Google Apps Script to import data from a CSV file where the datas are in a single column. I'm following this tutorial to read datas from CSV file but since the datas are in single column, comma delimiter is not working and the code is hanging whenever I run the function.
Here is my code:
function importCSV(getfile) {
getfile = "Copy of FR1_1.csv";
var getFolder = DriveApp.getFolderById(fId);
var fi = getFolder.getFilesByName(getfile);
if (fi.hasNext()) {
var ssNew = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = ssNew.getSheetByName("Sheet1");
var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
// loop through csv data array and insert (append) as rows into the sheet
for (var i = 0; i < csvData.length; i++) {
newSheet.getRange(newSheet.getLastRow()+1, 1, csvData.length).setValues(new Array(csvData[i][0]));
}
Browser.msgBox("CSV imported successfully!");
}
}
function CSVToArray(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to COMMA.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [
[]
];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData)) {
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
) {
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2]) {
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
}
// Return the parsed data.
return (arrData);
}
How can I import datas from a single column of CSV file in spreadsheet?
I have tried this code for single column and it works fine.
function importCSV() {
var getfile = "singleColumn.csv";
var getFolder = DriveApp.getFolderById(fId);
var fi = getFolder.getFilesByName(getfile);
if (fi.hasNext()) {
var ssNew = SpreadsheetApp.getActiveSpreadsheet();
var newSheet = ssNew.getSheetByName("csv");
var file = fi.next();
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv); // see below for CSVToArray function
// loop through csv data array and insert (append) as rows into the sheet
for (var i = 0; i < csvData.length; i++) {
newSheet.appendRow(csvData[i]);
//newSheet.getRange(newSheet.getLastRow()+1, 1, csvData.length,1).setValue(csvData[i][0]);
}
Browser.msgBox("CSV imported successfully!");
}
}
You may read more from this article.

GetRange() give a width error after 3000 rows

the getrange code give the error
Incorrect Range width, was 1 but should be 5
The CSV file has 8127 rows and when I broke up the file in 8 different files each containing 1000 rows and processed them separatly they all completed without any errors. But once i process a file greater than 3000+ rows it gets the above error message.
below is the get range code
ss.getRange(lastrow + 1,1,csvData.length,csvData[0].length).setValues(csvData);
I have also tried this but this gets an error stating exceeded maximum execution time:
for (var i = 0; i < csvData.length; i++) {
ss.getRange(i + 1,1,1,csvData[i].length).setValues(new Array(csvData[i]));
}
The CSV file is 2D.
Below is the full code:
Function getCSV() {
var fSource = DriveApp.getFolderById('0B2lVvlNIDosoajRRMUwySVBPNVE'); //reports_folder_id = id of folder where csv reports are saved
var date= Utilities.formatDate(new Date(), "GMT", "dd-MM-yy");
var fi = fSource.getFilesByName('L661_BOM-CAD_07-01-16.csv');
// latest report file
var ss = SpreadsheetApp.openById('1V8YG8lyNZiTllEPHENcnabYRLDPCK6mHGUyAyNhW0Is').getSheet s()[0]; // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data Sheet will be opened server side.
ss.getName() == "Sheet1"
if ( fi.hasNext()) { // proceed if "report.csv" file exists in the reports folder
var file = fi.next();
//file.setName('L661_BOM-CAD_'+ date +'(EXPORTED)'+'.csv');
var csv = file.getBlob().getDataAsString();
var csvData = CSVToArray(csv);
Logger.log('csvData[0].length: ' + csvData[0].length + ' csvData.length:' + csvData.length);
var lastrow = ss.getLastRow();
for (var i = 0; i < csvData.length; i++) {
ss.getRange(i + 1,1,1,csvData[i].length).setValues(new Array(csvData[i]));
}
}
if( ss.getName() == "Sheet1" ) { //checks that we're on the correct sheet
var r= ss.getRange('A1');
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 5);
if( nextCell.getValue() === '' ) //is empty?
var date = new Date();
var date= Utilities.formatDate(new Date(), "GMT", "dd-MM-yy");
nextCell.setValue(date); //enters the date in F1 in dd/mm/yyyy format
};
};
};
function CSVToArray( strData, strDelimiter ){
strDelimiter = (strDelimiter || ';');
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
var arrData = [[]];
var arrMatches = null;
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
strMatchedDelimiter !== strDelimiter
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
var strMatchedValue;
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
Logger.log('arrData[0].length: ' + arrData[0].length);
}
// Return the parsed data.
return( arrData );
}
Check the value of csvData[0].length again. It says length should be 5 but it gives 1.
Since it has more than 3000 records, it will exceed maximum execution time. setting values will take much time when it is on a loop. What you want to do is first get the values to an array and set them once later.
var myvalueArray = [];
for (var i = 0; i < csvData.length; i++) {
// do not set value here
//ss.getRange(i + 1,1,1,csvData[i].length).setValues(new Array(csvData[i]));
//push your values to an array
myvalueArray.push(csvData[i]);
}
once you push your values to defined array, set them once on your range.
ss.getRange(1,1,1,csvData[i].length).setValues(myvalueArray);