Home > Enterprise >  Sort Column - Excel Javascript
Sort Column - Excel Javascript

Time:11-18

I'm trying to figure out how to sort a column in Excel. I read here --> https://learn.microsoft.com/en-us/javascript/api/excel/excel.rangesort?view=excel-js-preview

But they don't give any useful example.

Here is a basic example I'm trying to figure out:

var ws = context.workbook.worksheets.getActiveWorksheet();
ws.getRange("A1").values = "B"
ws.getRange("A2").values = "A"
ws.getRange("A3").values = "C"
await context.sync()

var Used_Range = ws.getUsedRange(true)
await context.sync()
Used_Range.RangeSort.apply()

CodePudding user response:

This code will sort the range A1:A3 on the active worksheet by the first column in the range:

  await Excel.run(async (context) => {
    const sheet = context.workbook.worksheets.getActiveWorksheet();

    // Add values to the range
    const range = sheet.getRange("A1:A3");
    range.values = [["B"], ["C"], ["A"]];

    // Sort the range
    const sortFields = [
      {
        key: 0,
        ascending: true
      }
    ];
    range.sort.apply(sortFields);

    await context.sync();
 });

The difference between your code and this code is that the range.sort.apply method need to know which column to sort by and the sortfields array provide that information. Also, the method should be called before the context.sync() method is called.

  • Related