Saturday, June 10, 2023

Freeze top row using Openpyxl

import openpyxl

#freeze and unfreeze using openpyxl
#open zomato spreadsheet

work_book=openpyxl.load_workbook(r'C:\Users\allso\Desktop\new vba projects\openpyxl\zomato.xlsx')


#select active sheet

sheet=work_book.active

#freeze the top row
#all rows above the current row and all columns left to the current column will be frozen

sheet.freeze_panes="A2"

#save the work book

work_book.save(r'C:\Users\allso\Desktop\new vba projects\openpyxl\zomato.xlsx')


Convert csv to xlsx as openpyxl does not support .csv file format


import csv
from openpyxl import Workbook

wb = Workbook()
ws = wb.worksheets[0]
ws.title = "zomato"

with open(r'C:\Users\allso\Desktop\new vba projects\openpyxl\zomato.csv',encoding='cp437', errors='ignore') as f:
    reader = csv.reader(f)
    for row_index, row in enumerate(reader):
        for column_index, cell in enumerate(row):
            column_letter = column_index + 1
            cell_value = cell.replace('"', '')
            ws.cell(row = row_index + 1, column = column_letter).value = cell_value



wb.save(filename = r'C:\Users\allso\Desktop\new vba projects\openpyxl\zomato.xlsx')