Forum Discussion
Convert CSV to Excel Office Script
Instead of
let sheet = workbook.getWorksheet("Sheet1");
you may use
const sheet = workbook.getWorksheets()[0]
to return very first sheet (numbering starts from zero). You may check the sheet name by
console.log(sheet.getName())
Just in case, equivalent syntax is
let sheet = workbook.getWorksheets()[0];SergeiBaklan I replaced you suggestion now I am getting a different error? I am getting an error with line 8 csv = csv.replace("/\r/g, """);
Error is Line 8 Cannot read properties of undefined (reading 'replace')
- SergeiBaklanMay 01, 2023Diamond Contributor
I did a quick test, in general script if take sheet by number works
/** * Convert incoming CSV data into a range and add it to the workbook. */ function main(workbook: ExcelScript.Workbook, csv: string) { csv = `1, 2, 3 4, 5, 6 7, 8, 9`; //let sheet = workbook.getWorksheet("Sheet1"); const sheet = workbook.getWorksheets()[0] // Remove any Windows \r characters. csv = csv.replace(/\r/g, ""); // Split each line into a row. let rows = csv.split("\n"); /* * For each row, match the comma-separated sections. * For more information on how to use regular expressions to parse CSV files, * see this Stack Overflow post: https://stackoverflow.com/a/48806378/9227753 */ const csvMatchRegex = /(?:,|\n|^)("(?:(?:"")*[^"]*)*"|[^",\n]*|(?:\n|$))/g rows.forEach((value, index) => { if (value.length > 0) { let row = value.match(csvMatchRegex); // Check for blanks at the start of the row. if (row[0].charAt(0) === ',') { row.unshift(""); } // Remove the preceding comma. row.forEach((cell, index) => { row[index] = cell.indexOf(",") === 0 ? cell.substr(1) : cell; }); // Create a 2D array with one row. let data: string[][] = []; data.push(row); // Put the data in the worksheet. let range = sheet.getRangeByIndexes(index, 0, 1, data[0].length); range.setValues(data); } }); // Add any formatting or table creation that you want. }Lates error you have means script can't find csv (thus replace() on it has value 'undefined' ). You may reproduce such error with above script if to comment definition of csv like
/** * Convert incoming CSV data into a range and add it to the workbook. */ function main(workbook: ExcelScript.Workbook, csv: string) { /* csv = `1, 2, 3 4, 5, 6 7, 8, 9`; */ //let sheet = workbook.getWorksheet("Sheet1"); const sheet = workbook.getWorksheets()[0] // Remove any Windows \r characters. csv = csv.replace(/\r/g, ""); //....With that I may assume that the problem is in Power Automate flow which doesn't return csv content to the script. First I'd check the configuration - folder with csv files has exactly the same name as used in the flow, in that flow are actual csv files. Next, run flow , after it is finished click in history on that run and check inputs and outputs for steps on that run.