How to fix corrupted imported online excel in google sheet? - google-apps-script

I need this online excel:
https://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0
in my google sheet but when I use Importdata formula as below:
Importdata("https://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0")
it turns out to be imported in corrupted way like this:
enter image description here
but the original online file is this:
enter image description here
How Can I fix it?

I believe your goal as follows.
You want to put the values from the XLSX data downloaded from an URL to the active sheet of Google Spreadsheet.
Issue and workaround:
In the current stage, it seems that there are no method for directly retrieving the data from XLSX data of URL in the built-in functions for Google Spreadsheet. So in this answer, I would like to propose to achieve your goal using Google Apps Script. When Google Apps Script is used, your goal can be achieved.
The flow of the sample script is as follows.
Retrieve XLSX data.
Convert XLSX data to Google Spreadsheet as the temporal Spreadsheet.
Retrieve values from the converted Spreadsheet.
Put the values from the converted Spreadsheet to the active sheet.
Remove the temporal Spreadsheet.
Sample script:
Please copy and paste the following script to the script editor of the Google Spreadsheet. Before you use this script, please enable Drive API at Advanced Google services. And please run the function of myFunction at the script editpor. By this, the values of XLSX data are put to the active sheet.
function myFunction() {
// 1. Retrieve XLSX data.
const url = "https://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0"; // This is your URL.
const blob = UrlFetchApp.fetch(url).getBlob();
// 2. Convert XLSX data to Google Spreadsheet as the temporal Spreadsheet.
const id = Drive.Files.insert({title: "temp", mimeType: MimeType.GOOGLE_SHEETS}, blob).id;
// 3. Retrieve values from the converted Spreadsheet.
const values = SpreadsheetApp.openById(id).getSheets()[0].getDataRange().getValues();
// 4. Put the values from the converted Spreadsheet to the active sheet.
const dstSheet = SpreadsheetApp.getActiveSheet();
dstSheet.getRange(1, 1, values.length, values[0].length).setValues(values);
// 5. Remove the temporal Spreadsheet.
DriveApp.getFileById(id).setTrashed(true);
}
If you want to put the values to the specific sheet and range, please modify the script of 4. Put the values from the converted Spreadsheet to the active sheet..
References:
Files: insert
getValues()
setValues(values)

Related

Read a CSV from GitHub to Google sheets

Similar to this, I wish to read data stored in csv format in a GitHub repository directly into Google sheets.
An example of the data in question is here. When I tell google sheets to import the (raw) data from this url, it finds no matching file: .
Can a direct import be achieved this simply, or does it necessarily involve using an API?
In your situation, how about the following patterns?
Pattern 1:
In this pattern, IMPORTDATA is used. A sample formula is as follows. Please put this formula into a cell of Spreadsheet.
=IMPORTDATA("https://raw.githubusercontent.com/emagar/elecRetrns/master/data/pred1964-on.csv")
Pattern 2:
In this pattern, Google Apps Script is used. Please copy and paste the following script to the script editor of Spreadsheet and run the script. By this, the retrieved CSV data is put into the active sheet.
function myFunction() {
// Retrieve CSV data and parse it.
const url = "https://raw.githubusercontent.com/emagar/elecRetrns/master/data/pred1964-on.csv";
const str = UrlFetchApp.fetch(url).getContentText();
const ar = Utilities.parseCsv(str);
// Put the values into the active sheet.
const sheet = SpreadsheetApp.getActiveSheet(); // or SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
sheet.getRange(1, 1, ar.length, ar[0].length).setValues(ar);
}
References:
IMPORTDATA
fetch(url)
parseCsv(csv)
If you have to do that only once, this can be helpful -
Have you tried the following steps:
Copy and paste the data from Here to notepad
Save the notepad file as xyz.csv

How do i get google doc name from url in google sheet?

image of my sheet
This is my sheet image
I tried to search but didn't find any solution.
I believe your goal is as follows.
From your following sample spreadsheet (this image is from your question.),
You want to retrieve the URLs of Google Document files from the cells "B3:B", and you want to retrieve the document titles and want to put the document titles in the column "A".
In this case, how about the following sample script? Unfortunately, in the current stage, your goal cannot be achieved by the built-in functions. So, in this answer, Google Apps Script is used.
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet and set your sheet name to sheetName and save the script. And, please run myFunction with the script editor. And, please authorize the scopes. By this, the script is run. When this script is run, the google document URLs are retrieved from "B3:B" and converted the URLs to the document titles, and the titles are put into the column "A".
function myFunction() {
const sheetName = "Sheet1"; // Please set your sheet name.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const range = sheet.getRange("B3:B" + sheet.getLastRow());
const values = range.getDisplayValues().map(([url]) => [url ? DocumentApp.openByUrl(url).getName() : null]);
range.offset(0, -1).setValues(values);
}
Note:
In this script, your provided sample Spreadsheet is used. When you change your Spreadsheet, this script might not be able to be used. Please be careful about this.
In this script, it supposes that all URLs of "B3:B" are the URLs of Google Documents. Please be careful about this.
References:
map()
openByUrl(url)
getName()

Download Google Sheet to .xlsx Format using Link - multiple tabs

I need using the link to download the Google Sheet to .xlxs format.
This is works for me. but it is for single tab only, the thing is I have to download three or more tabs. I believe the format of "gid" would be different.
https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=1eVcHMWyH1YIDN_i0iMcv468c4_jnPk9Tw5gea-2FCyk&gid=626501804&exportFormat=xlsx
I believe your goal is as follows.
You want to export a Google Spreadsheet in XLSX format.
You want to include several specific Sheets in the Google Spreadsheet.
In this case, how about the following workaround? In this workaround, a Google Spreadsheet including the several sheets you want to include is created as a temporal Spreadsheet. In this case, as a simple method, Google Apps Script is used for retrieving the URL.
Sample script:
function sample() {
const exportSheetNames = ["Sheet1", "Sheet2", "Sheet3"]; // Please set the sheet names you want to export.
const spreadsheetId = "###"; // Please set your Spreadsheet ID.
const source = SpreadsheetApp.openById(spreadsheetId);
const temp = source.copy("temp_" + source.getName());
temp.getSheets().forEach(s => {
if (!exportSheetNames.includes(s.getSheetName())) temp.deleteSheet(s);
});
const url = `https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=${temp.getId()}&exportFormat=xlsx`;
console.log(url);
}
When this script is run, you can see the URL for exporting the Spreadsheet in XLSX format including the specific sheets you want at the log. From your question, I thought that you might want the URL for exporting.
This is a simple sample script for achieving your goal. For example, if you want to automatically export the XLSX file using a script, you can see the sample script at this thread.

Function to export only current sheet to Excel, with values and formats

I have this sample Google Spreadsheet.
I want to create a Google Apps Script function to export only the sheet named "TargetSheet" to Excel.
Since TargetSheet might have formulas, it is important that this exportation has only values. Also, the colors and formats are important to be kept.
The final file should look like this.
Someone suggested me to use this snippet to export the sheet, but since I'm a begginner in Google Apps Script I didn't quite understand how to do that. Should I copy it to my code? Should I import it somehow? And after getting this function to work in my script, I assume I would need to create a function to put that to work. Would that look like this below?
function exportarPlanilha() {
var spreadsheet = SpreadsheetApp.getActiveSheet();
var file = exportSpreadsheetToFile_(spreadsheet, 'xlsx');
return file;
}
You want to export one of sheet (TargetSheet) in the active Spreadsheet as a XLSX file.
From the sample script of URL in your question, you want to create the XLSX file in your Google Drive.
You want to achieve this using the sample script of URL in your question with Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Flow:
When I saw the sample script of URL in your question, it seems that the flow is as follows.
Copy the active Spreadsheet as a tempora Spreadsheet.
Convert the formulas to the texts.
Delete the sheets except for a sheet you want to export.
Retrieve the export URLs.
Retrieve the blob from the export URL.
Crete the blob as a file.
Delete the temporal Spreadsheet.
In your case, the export type is the XLSX format which is the constant. So I think that the process cost can be reduced a little. So the modified script is as follows.
Sample script:
Please copy and paste the following script to the script editor of the Spreadsheet. And please set exportSheetName. Then, please run the function exportarPlanilha at the script editor. When the authorization screen is displayed, please authorize the scopes. By this, the script is run.
function exportarPlanilha() {
const exportSheetName = 'TargetSheet'; // Please set the target sheet name.
// 1. Copy the active Spreadsheet as a tempora Spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet().copy('tmp');
// 2. Convert the formulas to the texts.
const targetRange = spreadsheet.getSheetByName(exportSheetName).getDataRange();
targetRange.copyTo(targetRange, {contentsOnly:true});
// 3. Delete the sheets except for a sheet you want to export.
spreadsheet.getSheets().forEach(sheet => {
if (exportSheetName != sheet.getName()) spreadsheet.deleteSheet(sheet)
});
// 4. Retrieve the blob from the export URL.
const id = spreadsheet.getId();
const xlsxBlob = UrlFetchApp.fetch(`https://docs.google.com/spreadsheets/export?id=${id}&exportFormat=xlsx`, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob();
// 5. Crete the blob as a file.
DriveApp.createFile(xlsxBlob.setName(`${exportSheetName}.xlsx`));
// 6. Delete the temporate Spreadsheet.
DriveApp.getFileById(id).setTrashed(true);
}
In this case, the temporal Spreadsheet is moved to the trash box.
Note:
In this case, please enable V8 at the script editor.
In above script, the XLSX file is created to the root folder. If you want to create the file to the specific folder, please tell me.
References:
copy(name)
copyTo(destination, options)
deleteSheet(sheet)
Class UrlFetchApp
createFile(blob)
setTrashed(trashed)
If I misunderstood your question and this was not the direction you want, I apologize.

Copy an entire Spreadsheet, Just Preserve the Values

I want to copy an entire spreadsheet of some 20+ sheets to a different location in Drive; however, I only want to preserve the hard values and formatting in each cell, and not the formulas (basically just taking a snapshot of the values). I have been playing around with how to write this but I don't have a solid idea on what's the best approach. I'm just starting to learn conditionals like looping in my google sheets training, any help would be appreciated. Thanks!
Those cells in green are all vlookups and they update from an array I have on another spreadsheet. The idea is to get all the right data in the array, have this sheet fully fill out with the correct values for the day, then save it preferably as a google sheet but just the values, so that they are editable after the fact if there was an error in the array data.
You want to copy the source Spreadsheet in the specific folder in your Google Drive.
You want to use a date stamped on it for a name as the filename.
You don't want to copy the formulas. You want to copy only displaying values.
In your Spreadsheet, the formulas of many vlookups and other outside reference cells are included.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
The flow of the sample script for the above goal is as follows.
Flow:
Copy all sheets in the source Spreadsheet as the temporal sheets.
At the copied sheets, the cells are overwritten by only the values. By this, the formulas can be removed.
Copy the source Spreadsheet.
Delete the temporal sheets in the source Spreadsheet.
Delete the original sheets in the destination Spreadsheet.
Move the copied Spreadsheet to the specific folder.
Sample script:
Before you run the script, please set the source Spreadsheet ID and the destination folder ID.
function myFunction() {
var spreadsheetId = "###"; // Please set the source Spreadsheet ID.
var destFolderId = "###"; // Please set the destination folder ID.
// Copy each sheet in the source Spreadsheet by removing the formulas as the temporal sheets.
var ss = SpreadsheetApp.openById(spreadsheetId);
var tempSheets = ss.getSheets().map(function(sheet) {
var dstSheet = sheet.copyTo(ss).setName(sheet.getSheetName() + "_temp");
var src = dstSheet.getDataRange();
src.copyTo(src, {contentsOnly: true});
return dstSheet;
});
// Copy the source Spreadsheet.
var destination = ss.copy(ss.getName() + " - " + new Date().toLocaleString());
// Delete the temporal sheets in the source Spreadsheet.
tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
// Delete the original sheets from the copied Spreadsheet and rename the copied sheets.
destination.getSheets().forEach(function(sheet) {
var sheetName = sheet.getSheetName();
if (sheetName.indexOf("_temp") == -1) {
destination.deleteSheet(sheet);
} else {
sheet.setName(sheetName.slice(0, -5));
}
});
// Move file to the destination folder.
var file = DriveApp.getFileById(destination.getId());
DriveApp.getFolderById(destFolderId).addFile(file);
file.getParents().next().removeFile(file);
}
Note:
In this sample script, the script of this answer was used.
This is a simple sample script. So please modify this for your actual situation.
References:
copy(name)
copyTo(destination, options)
map()
forEach()
addFile()
removeFile()
If you actually plan on using this data you probably want to think twice of just randomly copying everything. If you want to just archive Just add export?format=zip to the end of your link, then you will have a saved copy with values and formatting.
Another very simple way is to Download the sheet to Excel. It will keep local formulas but remove external references (like importrange, etc), so data will stay frozen ;)
You can even open the Excel file from Gsheets (without converting it to sheets).