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')
Saturday, June 10, 2023
Freeze top row using Openpyxl
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')
Saturday, January 14, 2023
Openpyxl part 4,writing to excel file using openpyxl
#creating new workbook
work_book=openpyxl.Workbook()
#to see the active sheet
print(work_book.active)
#create a handle to the sheet
sheet=work_book['Sheet']
#write value in individual cells
sheet['A1']='Hello'
sheet['B1']='Excel'
sheet['C1']='Users!'
print(sheet['A1'].value)
print(sheet['B1'].value)
print(sheet['C1'].value)
#save the workbook
#work_book.save(r'C:\Users\allso\Desktop\new vba projects\openpyxl\example.xlsx')
import os
print("File location using os.getcwd():", os.getcwd())
work_book.save('example.xlsx')
#get cells in the sheet which contains data
print(sheet.calculate_dimension())
#add data after the dimension
sheet.append(['One','row','of','text'])
#get cells in the sheet which contains data
print(sheet.calculate_dimension())
#save the workbook
work_book.save(r'C:\Users\allso\Desktop\new vba projects\openpyxl\example.xlsx')
Sunday, January 1, 2023
Openpyxl intro,open an existing xlsx and print the number of sheets as well as the first cell's content in the first sheet
import openpyxl
work_book=openpyxl.load_workbook(r'C:\Users\allso\Desktop\new vba projects\openpyxl\countries.xlsx')
print(work_book.sheetnames)
sheet_obj=work_book['Sheet1']
print(sheet_obj.title)
print(sheet_obj['A1'])
cell=sheet_obj['B1']
print(cell.value)
print(cell.row)
print(cell.column)