pip install openpyxl
from openpyxl import Workbook wb = Workbook() # create a new workbook that contains sheets ws = wb.active # get access to active (default) sheet ws.title = "Products" # Change title of the sheet # place data in different cells ws['A1'] = 'Name' ws['B1'] = 'Price' ws['A2'] = 'iPhone 14 Pro' ws['B2'] = 120000 ws['A3'] = 'AirPods 3rd Gen' ws['B3'] = 20000 wb.save('products.xlsx') # save workbook to products.xlsx file in the current directory
from openpyxl import load_workbook wb = load_workbook(filename='products.xlsx') # Open file products.xlsx ws = wb["Products"] # Access sheet with name Products # display values from specific cells - a2 and b2 print(f"{ws['a2'].value} - {ws['b2'].value}")
from openpyxl import load_workbook wb = load_workbook(filename='products.xlsx') # Open file products.xlsx ws = wb["Products"] # Access sheet with name Products from openpyxl import load_workbook wb = load_workbook(filename='products.xlsx') ws = wb["Products"] # Access sheet with name Products for row in ws.iter_rows(min_row=2, max_col=2, max_row=3): for cell in row: print(cell.value)
from openpyxl import load_workbook wb = load_workbook(filename='products.xlsx') # Open file products.xlsx ws = wb["Products"] # Access sheet with name Products from openpyxl import load_workbook wb = load_workbook(filename='products.xlsx') ws = wb["Products"] # Access sheet with name Products # values returns a collection of tuples, where each tuple represents a row and contains values of columns for row in ws.values: for cell in row: print(cell)
from openpyxl import load_workbook import json wb = load_workbook(filename='products.xlsx') ws = wb["Products"] # Access sheet with name Products headings = [ws['a1'].value, ws['b1'].value] # take values from first row products = [] for row in ws.iter_rows(min_row=2, max_col=2, max_row=3): # take two rows from 2nd row # convert each row to a dict by using heading as key and cell value as value product = {} for heading, cell in zip(headings, row): product[heading] = cell.value products.append(product) # add dict to list # Convert a list of dict to an array of JSON Objects print(json.dumps(products)) # Write JSON array to file json.dump(products, open("products.json","wt"))
from openpyxl import load_workbook import sqlite3 # connect to database con = sqlite3.connect(r"c:\dev\python\test.db") cur = con.cursor() # Open Excel file and access sheet wb = load_workbook(filename='products.xlsx') ws = wb["Products"] # Access sheet with name Products for row in ws.iter_rows(min_row=2, max_col=2, max_row=3): values = [] # create a list that contains values of current row for cell in row: values.append(cell.value) # insert a row into PRODUCTS table. Convert list to tuple and pass it as second parameter for execute() cur.execute("insert into products(name, price) values(?, ?)", tuple(values)) # make insertions permanent con.commit() # close connection and cursor cur.close() con.close()