I believe your current situation and your goal are as follows.
- You have a sheet on a Google Spreadsheet. The cells of the sheet have the number formats you manually set.
- You want to put CSV data on this sheet.
- When the CSV data is put to the sheet, you want to keep the manually set number formats of the cells.
I had had the same issue with your situation. In this case, when the CSV data is manually put using the default UI, it seems that the number formats of all cells cannot be kept. So, at that time, I used a workaround. This workaround uses Google Apps Script. When Google Apps Script is run, a dialog is opened. And, the CSV file is loaded, and then, the CSV data is put to the active cell with keeping the number formats.
When this workaround is reflected in a Google Apps Script, it becomes as follows.
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet, and save the script. And, please run onOpen with the script editor. By this, the custom menu is created. After this, when you select a cell and run the script from run of the custom menu, the dialog is opened. And, when you select the CSV file, the CSV data is retrieved and put from the active cell. At that time, the CSV data is put while the number formats of the cells are kept.
function onOpen() {
SpreadsheetApp.getUi().createMenu("sample").addItem("run", "insertCSVdata").addToUi();
}
function insertCSVdata(e) {
if (!e) {
const html = HtmlService.createHtmlOutput(`<input type="file" id="csv" value="Select CSV file" accept=".csv,text/csv" onchange="main()"><script>function main(){const file=document.getElementById("csv").files[0]; const fr=new FileReader(); fr.readAsArrayBuffer(file); fr.onload=(f)=> google.script.run.withSuccessHandler(google.script.host.close).insertCSVdata([[...new Int8Array(f.target.result)], file.name, file.type]);}</script>`);
SpreadsheetApp.getUi().showModalDialog(html, "sample");
return;
}
const activeRange = SpreadsheetApp.getActiveRange();
const csv = Utilities.newBlob(...e).getDataAsString();
const ar = Utilities.parseCsv(csv);
const range = activeRange.offset(0, 0, ar.length, ar[0].length);
const formats = range.getNumberFormats().map(r => r.map(c => c || "@"));
range.setValues(ar).setNumberFormats(formats);
return;
}
- In this sample script, the number formats of the cells are copied and put the CSV data to the cells, and then, the copied number formats are pasted. By this flow, the number formats of cells are kept.
Note:
In this sample script, HTML and Javascript is as follows.
<input type="file" id="csv" value="Select CSV file" accept=".csv,text/csv" onchange="main()">
<script>
function main() {
const file = document.getElementById("csv").files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = (f) => google.script.run.withSuccessHandler(google.script.host.close).insertCSVdata([[...new Int8Array(f.target.result)], file.name, file.type]);
}
</script>
References: