How to move a copied worksheet to the first position? - python

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')

Related

How to create autonumbering with Python in Openpyxl

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')

How to write the data that has been read into a certain column using openpyxl

I cannot figure out how to write the data that has been read below to a certain column, such as column F. Column B has been read and I want to paste it in the same workbook into column F. Eventually I would create a function because I would be doing the reading and writing columns multiple times.
import openpyxl
import os
# Finds current directory
current_path = os.getcwd()
print(current_path)
# Changes directory
os.chdir('C:\\Users\\Shane\\Documents\\Exel Example')
# prints new current directory
new_path = os.getcwd()
print(new_path)
# load workbook
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
# load worksheet
ws1 = wb.active
# read sheet names
sht_names = wb.sheetnames
print(sht_names)
# ***reads and prints column B***
col_b = list(ws1.columns)[1]
for cellObj in col_b:
print(cellObj.value)
# write column b's contents into column F
from openpyxl import load_workbook
t = load_workbook("test.xlsx")
s = t.active # get the active worksheet
lst = list(s.columns)
lst_row = list(s.rows)
cellA1 = s[1][0]
rowA = s[1]
g = (x.value for x in lst[1]) # column b?
for item in g:
print (item)

How to filter column data using openpyxl

I am trying to apply a filter to an existing Excel file, and export it to another Excel file. I would like to extract rows that only contain the value 16, then export the table to another excel file (as shown in the picture below).
I have tried reading the openpyxl documentation multiple times and googling for solutions but I still can't make my code work. I have also attached the code and files below
import openpyxl
# Is use to create a reference of the Excel to wb
wb1 = openpyxl.load_workbook('test_data.xlsx')
wb2 = openpyxl.load_workbook('test_data_2.xlsx')
# Refrence the workbook to the worksheets
sh1 = wb1["data_set_1"]
sh2 = wb2["Sheet1"]
sh1.auto_filter.ref = "A:A"
sh1.auto_filter.add_filter_column(0, ["16"])
sh1.auto_filter.add_sort_condition("B2:D6")
sh1_row_number = sh1.max_row
sh1_col_number = sh1.max_column
rangeSelected = []
for i in range(1, sh1_row_number+1, 1):
rowSelected = []
for j in range(1, sh1_col_number+1, 1):
rowSelected.append(sh1.cell(row = i, column = j))
rangeSelected.append(rowSelected)
del rowSelected
for i in range(1, sh1_row_number+1, 1):
for j in range(1, sh1_col_number+1, 1):
sh2.cell(row = i, column = j).value = rangeSelected[i-1][j-1].value
wb1.save("test_data.xlsx")
wb2.save("test_data_2.xlsx")
The pictures shows what should be the desire result
The auto filter doesn't actually filter the data, it is just for visualization.
You probably want to filter while looping through the workbook. Please note with this code I assume you have the table headers already in the second workbook. It does not overwrite the data, it appends to the table.
import openpyxl
# Is use to create a reference of the Excel to wb
wb1 = openpyxl.load_workbook('test_data.xlsx')
wb2 = openpyxl.load_workbook('test_data_2.xlsx')
# Refrence the workbook to the worksheets
sh1 = wb1["data_set_1"]
sh2 = wb2["data_set_1"] # use same sheet name, different workbook
for row in sh1.iter_rows():
if row[0].value == 16: # filter on first column with value 16
sh2.append((cell.value for cell in row))
wb1.save("test_data.xlsx")
wb2.save("test_data_2.xlsx")

Python-Excel: How to write lines of a row to an existing excel file?

I have searched the site but I could not find anything related to the following question.
I have an existing spreadsheet that I am going to pull data from on a daily basis, the information in the spreadsheet will change everyday.
What I want to do is create a file that tracks certain information from this cell, I want it to pull the data from the spreadsheet and write it to another spreadsheet. The adding of the data to a new spreadsheet should not overwrite the existing data.I would really appreciate the help on this. See code below:
import os
import openpyxl
import xlrd
wb=openpyxl.load_workbook('Test_shorts.xlsx','r')
sheet = wb.active
rows = sheet.max_row
col = sheet.max_column
rows = rows+1
print rows
new =[]
for x in range (2, 3):
for y in range(1,10):
z= sheet.cell(row=x,column=y).value
new.append(z)
print(new)
If you want to copy the whole worksheet, you can use copy_worksheet() function directly. It will create a copy of your active worksheet.
I don't know your data, but I am sure you can finish it by yourself. Hope this may help
from openpyxl import load_workbook
file_name = "Test_shorts.xlsx"
wb = load_workbook(file_name)
sheet = wb.active
target = wb.copy_worksheet(sheet)
# you can code to append new data here
new = wb.get_sheet_by_name(target.title) # to get copied sheet
for x in range (2, 3):
for y in range(1,10):
print(x,y)
z= sheet.cell(row=x,column=y).value
new.append(z)
wb.save(file_name)
as commented, a loop of cells are required so I altered your code a little.
from openpyxl import load_workbook
file_name = "Test_shorts.xlsx"
wb = load_workbook(file_name)
current_sheet = wb.active
new_sheet = wb.create_sheet("New", 1)
for row in current_sheet.rows:
col = 0 # set the column to 0 when 1 row ends
for cell in row:
col += 1 # cell.column will return 'ABC's so I defined col for the column
new_sheet.cell(cell.row, col, cell.value)
wb.save(file_name)

I want to update the last row in an excel spreadsheet, daily. OpenPyXl

The following is an excerpt from a function (whose remaining body has been excluded; nothing to do with this issue and has already been tested to make sure has no faults).
Objective: Get "val1a" (a dollar value acquired from another part of the function) and "t" to update daily to an excel spreadsheet.
Right now, I have them mapped to the A2 and B2 cells, respectively. I can't figure out how to make them populate the latest row, whenever the function is run. (A2:B2, A3:B3, and so on...)
t = date.today()
ts = datetime.time(datetime.now())
wb = load_workbook('val1a.xlsx')
sheet = wb.worksheets[0]
# grab the active worksheet
ws = wb.active
ws['A1'] = 'PRICE'
ws['B1'] = 'DATE'
ws['C1'] = 'FED'
ws['D1'] = 'CTD'
ws['A2'] = val1a
ws['B2'] = t
# Save the file
wb.save('a1 ' + str(t) + ".xlsx")
# how to read values in excel
read1 = ws['A2'].value
ws.append() always puts values in the next row of a spreadsheet.

Categories