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

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

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

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

Find and replace in cells from excel in python

Where I have a cell in an .xlsx file that is "=..." I want to replace the "=" with '=, so can see the cells as strings rather than as the values.
For example,
A1 = 5
A2 = 10
A3 = (A1/A2) = 0.5
I want to see =A1/A2 rather than 0.5.
Thank you in advance for any and all help.
As suggested openpyxl solves this problem:
import openpyxl
from openpyxl.utils.cell import get_column_letter
wb = openpyxl.load_workbook('example.xlsx')
wb.sheetnames
sheet = wb["Sheet1"]
amountOfRows = sheet.max_row
amountOfColumns = sheet.max_column
for i in range(amountOfColumns):
for k in range(amountOfRows):
cell = str(sheet[get_column_letter(i+1)+str(k+1)].value)
if( str(cell[0]) == "="):
newCell = "'=,"+cell[1:]
sheet[get_column_letter(i+1)+str(k+1)]=newCell
wb.save('example_copy.xlsx')

Openpyxl observing the max_row of a sheet?

Is it possible to observe the max row of a sheet for changes? I have some functions I'd like to run everytime that value is updated (they would be the observers).
Does openpyxl support that?
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('yourFile.xlsx')
ws = wb['Sheet1']
initial_max_value = ws.max_row
while ws.max_row == inital_max_value:
THE
CODE
YOU
WANT TO WATCH
Else:
Print ('Max Value changed by ' + inital_max_value - ws.max_row

python program with output in an excel spreadsheet

I am trying to write the output retrieved from a large Excel workbook in another spreadsheet using Python. However, I am not able to, it's giving me errors such as raise ValueError("column index (%r) not an int in range(256)" % arg)ValueError: column index (256) not an int in range(256), Exception: Unexpected data type .
I can understand these errors to some extent but not able to rectify my code. I have written a small script here. It will be great if some one can tell me and correct me where I am going wrong.
import xlrd
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "path/lookup_V1.xlsx"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
print sheet1.name
sheet2 = workbook.sheet_by_index(1)
print sheet2.name
print workbook.nsheets
st1c=sheet1.ncols
st2r=sheet2.nrows
st1=st1c+1
st2=st2r+1
print("fill..")
for i in xrange(0,st1c):
s1=sheet1.col_values(i)
i+1
s1.sort()
print s1
for col in xrange(st1c):
for row in xrange(st2r):
print("filling sheet...")
col=col+1
row=row+1
ws.write(row,col)
print("here")
wb.save('testfile.xls')
Try this :
import xlrd
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "test.xls"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
st1c=sheet1.ncols
st1r=sheet1.nrows
for col in xrange(st1c):
for row in xrange(st1r):
value = sheet1.col_values(col, row, row + 1)
# According to documentation : http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Sheet.col_values-method
# col_values returns a slice of the values of the cells in the given column.
# That why we have to specify the index below, it is no elegant but it works
ws.write(row, col, value[0])
wb.save('testfile.xls')
This solution work for a single sheet... You may then convert it into a function and iterate over different sheets and workbook...
More elegant solution :
import xlrd
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('A Test Sheet')
file_location = "test.xls"
workbook=xlrd.open_workbook(file_location)
sheet1 = workbook.sheet_by_index(0)
st1c=sheet1.ncols
st1r=sheet1.nrows
for col in xrange(st1c):
for row in xrange(st1r):
# More elegant
value = sheet1.cell_value(row, col)
ws.write(row, col, value)
wb.save('testfile.xls')

Categories