Swap columns in Excel effortlessly with Python automation! πŸ”„ Simplify your data management tasks with ease.

Codingmadeeasy
2 min readApr 22, 2024

#python #excel #automation #coding #programming

Swapping columns in Excel manually can be tedious, especially when dealing with large datasets. Python automation can simplify this task by allowing you to write a script that automatically swaps the contents of two columns. In this tutorial, we will use the openpyxl library to create a Python script that swaps two columns in an Excel file effortlessly.

To begin, we will first create a new Excel workbook and add some sample data to it. Then, we will define a function that swaps the contents of two specified columns. Finally, we will save the modified Excel file with the swapped columns. This automation can save you time and effort, especially when working with Excel files regularly.

Let us take a excel sheet which has columns as Name,Age and Gender. the excel sheet is arranged in the manner below, we have to swap the columns

from openpyxl import Workbook

# Create a new Excel workbook
wb = Workbook()
ws = wb.active

# Add data to the Excel sheet
data = [
['Name', 'Age', 'Gender'],
['Alice', 25, 'Female'],
['Bob', 30, 'Male'],
['Charlie', 35, 'Male'],
['David', 40, 'Male'],
['Eve', 45, 'Female'],
['Frank', 50, 'Male'],
['Grace', 55, 'Female'],
['Helen', 60, 'Female'],
['Ivy', 65, 'Female']
]

for row in data:
ws.append(row)

# Swap columns (e.g., swap columns 'A' and 'B')
def swap_columns(sheet, col1, col2):
for i in range(1, sheet.max_row + 1):
# Get the values of the cells in the two columns
cell1 = sheet[col1 + str(i)].value
cell2 = sheet[col2 + str(i)].value
# Swap the values
sheet[col1 + str(i)] = cell2
sheet[col2 + str(i)] = cell1

# Swap columns 'A' and 'B'
swap_columns(ws, 'A', 'B')

# Save the workbook
wb.save('data.xlsx')

Read More Below

https://codemagnet.in/2024/04/22/swap-column-in-excel-with-ease-using-python-automation/

--

--