Home > Net >  write_dynamic_array_formula() formula works but I have to press enter to apply
write_dynamic_array_formula() formula works but I have to press enter to apply

Time:01-25

I have a table containing coordinates with associated labels A, B and C. I want to add another column that simply translates the labels to 1, 2 and 3.

import xlsxwriter

# Create some example data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
labels = ["A", "B", "C", "B", "A"]

# Create a new Excel file and add a worksheet
workbook = xlsxwriter.Workbook('scatter_plot.xlsx')
worksheet = workbook.add_worksheet('Data')

# write column headings
worksheet.write(0,0,'x')
worksheet.write(0,1,'y')
worksheet.write(0,2,'labels')


# Write the data to the worksheet
for i in range(len(x)):
    worksheet.write(i 1, 0, x[i])
    worksheet.write(i 1, 1, y[i])
    worksheet.write(i 1, 2, labels[i])

# Formula that writes a new column where A = 1 B = 2 C = 3    
worksheet.write_dynamic_array_formula('D2:D6', '=IFS(LEFT(C2:C6,1)="A",1,LEFT(C2:C6,1)="B",2,LEFT(C2:C6,1)="C",3,TRUE,NA())')    

# Add a scatter chart to the worksheet
chart = workbook.add_chart({'type': 'scatter'})
chart.add_series({
    'name':       'X vs Y',
    'categories': '=Data!$A$2:$A$6',
    'values':     '=Data!$B$2:$B$6',
    
})

# Insert the chart into the worksheet
worksheet.insert_chart("F1", chart)

# Save the Excel file
workbook.close()

I run this and get this excel file output:enter image description here

For more information see the Formulas added in Excel 2010 section of the XlsxWriter docs.

  • Related