How to create autonumbering with Python in Openpyxl - python

I am trying to create an automatic numbering system with leading zeros in Python and openpyxl.
What is the best way to define the columns?
I would like to name them first and then say for each column what needs to be done.
Go to column 1 and put a numbering in it from 00001 to 00500.
Go to column 2 and put a numbering in there from 00501 to 01000.
...
In my opinion if I have these I can make any variants I want.
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.active
ws.title = "Numbers"
ws.append(['N1','N2'])
#create Leading zero's
#zero_filled_number = number_str.zfill(5)
#print(zero_filled_number)
# Here I get stuck
for i in ws.append_columns(0)
i = range (1,500,1) number_str.zfill(5)
#ws.append_columns(1)
#for N2 in range (501,1000,1) number_str.zfill(5)
wb.save('Auto_numbers.xlsx')

from openpyxl import Workbook
import openpyxl
wb = Workbook()
sheet = wb.active
test_file = openpyxl.load_workbook('test.xlsx')
sheet = test_file.active
sheet['A1'] = 'ID'
counter = sheet.max_row
while counter < 10:
for row in sheet.rows:
counter += 1
sheet[f'A{counter}'] = f'N{counter}'
sheet.append([f'N{counter}'])
test_file.save('test.xlsx')

Related

Store cell value of first few characters

I am trying to change the name of a sheet according to the value of a cell.
here is the code I am using.
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb['Sheet 1']
sheet_name = ws['B2']
ws.title = f'Marketing {sheet_name}'
This code works, but
my problem is I only need to extract the first 3 characters from the cell ws['B2'].
How can I do that.
Use slicing:
sheet_name = ws['B2'].value[:3]
You can use the characters in the string.
Edit the parameters to get the desired result.
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb['Sheet 1']
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}' # First character to third
Start reading the tabs by number so you don't have to change the tab name in the future.
Final code:
from openpyxl import load_workbook
wb = load_workbook('file_name.xlsx')
ws = wb.worksheets[0] # First tab
sheet_name = ws['B2'].value
ws.title = f'Marketing {sheet_name[0:3]}' # First character to third

how to assign a list value to column in excel file?

I have a list value and want to assign it into a column in a excel file. The values I want to change are in sheet 6.
my poor code looks something like this the best I could do is try to first change the AF6:AF22 to a fixed value 5 with hope that I could change it to list.
But is there a simple way to change AF6:AF22 values to a list?
something simple ws['AF6:AF22'] = l?
from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook
l = list(range(5))
FilePath = 'excel_file.xlsx'
wb = load_workbook(FilePath)
ws = wb.worksheets
sheet_number = 6
for sheet_number in ws.iter_cols('AF6:AF22'):
for cell in sheet_number:
cell.value = 5
Option 1
Hi - I am adding a faster way here. This is probably better as it avoids the for loop and updating cells one at a time.
from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook
l = list(range(17)) #The list - You can replace l with whatever you need
with pd.ExcelWriter('excel_file.xlsx', mode='a', engine = 'openpyxl') as writer:
pd.DataFrame(l).to_excel(writer, sheet_name='Sheet6', startrow = 5, startcol= 31, index=False, header=None)
Option 2
You can use the below code to do what you need. Added comments, so you get an understanding of my logic...
from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook
l = list(range(17)) #The list - You can replace l with whatever you need
FilePath = 'excel_file.xlsx'
wb = load_workbook(FilePath)
ws = wb.worksheets[5] #Worksheet 5 is the 6th sheet as numbering starts from zero
for i in range(6,23): # Column numbers 6 through 22
ws.cell(row=i, column=32).value = l[i-6] #Write to cell in AF = column 32
wb.save("excel_file.xlsx")

Exporting to Excel Using Openpyxl - specific rows and columns

I have tried succesfuly to populate the data in QTableWidget using Pandas.
Now i want to export to specific rows and columns to an existing excel so i will not lose stylesheet and other data from this excel. Please , help me out finding the solution to run it properly.
Goal is to export to excel to specific rows and columns, rows in range from 7 to 30 and columns from 1 to 13 using OpenPyxl to just modify values of an existing excel. I know "appends" means to add whole data table on the bottom of the excel and i don't know what function to use instead.
def kalkuacje_exportuj(self):
columnHeaders = []
# create column header list
for j in range(self.ui.tableWidget.model().columnCount()):
columnHeaders.append(self.ui.tableWidget.horizontalHeaderItem(j).text())
df = pd.DataFrame(columns=columnHeaders)
# create dataframe object recordset
for row in range(self.ui.tableWidget.rowCount()):
for col in range(self.ui.tableWidget.columnCount()):
df.at[row, columnHeaders[col]] = self.ui.tableWidget.item(row, col).text()
from openpyxl import Workbook
wb = Workbook()
wb = load_workbook ('OFERTA_SZABLON.xlsx')
# ws1 = wb.sheetnames()
ws1 = wb["DETALE wyceniane osobno"]
# for row in ws1.iter_rows(min_row=7,
# max_row=30,
# min_col=1,
# max_col=13):
for row in range(7, 30):
for col in range(1, 13):
for r in dataframe_to_rows(df, index=False, header=False):
ws1.append(r)
# for cell in row:
# print(cell)
wb.save('OFERTA_SZABLON.xlsx')
I solved the problem like this:
from openpyxl import Workbook
wb = Workbook()
wb = load_workbook ('OFERTA_SZABLON.xlsx')
# ws1 = wb.sheetnames()
ws1 = wb["DETALE wyceniane osobno"]
# for r in dataframe_to_rows(df, index=False, header=False):
# ws1.append(r)
offset_row = 5
offset_col = 0
row = 1
for row_data in dataframe_to_rows(df, index=False, header=False):
col = 1
for cell_data in row_data:
ws1.cell(row + offset_row, col + offset_col, cell_data)
col += 1
row += 1
wb.save('OFERTA_SZABLON.xlsx')
I cannot figure this out for the life of me.
the guy above me has an error with >>> load_workbook ('OFERTA_SZABLON.xlsx')
it makes no sense and Workbook.load_workbook('') isn't a thing anyways
dataframe_to_rows doesn't seem to exist either

How to move a copied worksheet to the first position?

I would like to copy an Excel worksheet in Python using openpyxl. However, it defaults to placing the copied worksheet at the end. I want it at the front. The copy_worksheet doesn't allow specifying the position, unlike create_sheet. I'd rather not have to recreate the template.
I've considered sorting the sheets, but I'm not sure how to implement that.
Suppose I have a file called number.xlsx with an existing worksheet titled "blank" that I want to copy.
from openpyxl import load_workbook
from datetime import datetime
n = float(input("Number: "))
today = datetime.now()
m = today.month
d = today.day
y = str(today.year)
wb = load_workbook('number.xlsx')
if y in wb.sheetnames:
ws = wb[y]
ws.cell(row = 2 + d, column = 1 + m).value = n
wb.save('number.xlsx')
else:
ws = wb.copy_worksheet(wb["blank"]) #I want the copied sheet at the front, not the back
ws.title = y
ws.cell(row = 2 + d, column = 1 + m).value = n
wb.save('number.xlsx')
You can use move_sheet(sheet, offset=0) method for this. Here offset calculated as "current sheet index" + offset. Copy worksheet will add the sheet to the last of the workbook. So you need to give negative value to move sheet to index 0.
from openpyxl import load_workbook
wb = load_workbook("text.xlsx")
ws = wb.copy_worksheet(wb["sample"])
ws.title = "NewNameForCopiedSheet"
wb.move_sheet("NewNameForCopiedSheet", -(len(wb.sheetnames)-1))
I am posting an example
wb._sheets is what you use to control the order of tabs/sheets.
Get the position of sheet you want to rearrange and modify the list of sheets with new positions.
from openpyxl import Workbook
wb=Workbook()
# wb.create_sheet("Sheet")
wb.create_sheet("Sheet2")
wb.create_sheet("Sheet3")
wb.create_sheet("SheetA")
wb.create_sheet("ASheet")
wb.create_sheet("blank")
wb.save('book_original.xlsx')
blank_sheet_position = wb.worksheets.index(wb['blank'']) #get position of new sheet
blank_sheet_new_position = 0 #position where you want to move
sheets = wb._sheets.copy()
sheets.insert(blan_sheet_new_position, sheets.pop(blank_sheet_position))) #modifying the sheets list
wb._sheets = sheets
wb.save('book_myorder.xlsx')

How to iterate through all cells in first 3 columns in openpyxl

I'm hving trouble doing so
Right now i can get all rows in my sheet by:
from openpyxl import *
sheet = load_workbook(location)["Sheet1"]
for i in sheet:
for j in i:
print(j.value)
How can i do so in just the first 3 columns?
I suggest using this site: https://openpyxl.readthedocs.io/en/stable/tutorial.html
anyhow, this is the snippet:
from openpyxl import *
wb = Workbook()
ws = wb.active
for cell in ws.iter_rows(min_row=1, max_col = 3):
.
.
.
you can also use ws.iter_rows to access just the values
from openpyxl import *
wb = Workbook()
ws = wb.active
for cell in ws.iter_rows(min_row=1, max_col = 3, values_only = True):
print(cell) if cell else continue

Categories