Win32com library to automate excel using Python not recognizing highlighted cell? - python

I am using Win32 python library to automate excel. I basically have a loop going in and executing a specific macro in all of these excel workbooks. In this loop I also want to check if a specific sheet in the workbooks have any cells highlighted red, which would indicate an error. I don't know why the code is not working
Here is what I tried.
for location in loc_string:
xl = win32com.client.Dispatch('Excel.Application')
xl.Visible = True
xl.Workbooks.Open(rpt_file.format(location=location))
sheet = xl.Workbooks.Open(rpt_file.format(location=location)).Sheets[0]
for row in range(1, sheet.UsedRange.Rows.Count + 1):
for col in range(1, sheet.UsedRange.Columns.Count + 1):
cell = sheet.Cells(row, col)
# Check if the cell's fill color is red
if cell.Interior.ColorIndex == 3:
print(f"{location} has an error")
xl.Workbooks.Close()
xl.Application.Run("btnExportSageJE")
xl.Workbooks.Close()
xl.quit()
Thanks!

Related

How can I copy a range of data in excel (B2:B15) down with openpyxl?

I'm a Python beginner and I made a script to extract data into an xlsx file with openpyxl but I'm stuck with a problem which seems pretty easy. I'd like to copy(not move) the yellow data to the green cells in the following Excel file:
Or said in another way, I want to copy B2:B15 to B16:B29 within my python script. I don't need help with the import of openpyxl or creation of my ws it´s just the specific code that allows to copy the B2:B15 to B16:B29 which I don't get.
I appreciate any help! Ty so much.
I tried the following which didn´t work at all:
for row in range(16,29):
for col in range(1,2):
char = get_column_letter(col)
ws[char + str(row)] = ws(['B2:B15'].value)
If ws is your worksheet, then the code to do that is...
for row in range(16,30):
ws.cell(row=row, column=2).value = ws.cell(row=row-14, column=2).value
Updated below for doing this multiple times
Repeat = 5 #Indicate how many times you want to paste the 15 rows
for cycle in range(1, Repeat+1):
for row in range(14):
ws.cell(row=row+2+(cycle)*14, column=2).value = ws.cell(row=row+2, column=2).value

Python openpyxl not writing to cell

I am trying to read a value from an excel say A1 == 4 and using these
wb = load_workbook("GameExcel.xlsx")
names = wb.sheetnames
sheet = wb['GameEnviroment']
sheet['C4'].value
and it reads the information of the current cell just fine, but it doesn't want to write to the cell. There are no errors, it just doesn't work. this is the write code
C3Val = sheet['C4'].value
sheet.cell(row=3, column=4).value = (C3Val + ' 3')
As said by PRMoureu in the comments above, I needed to run wb.save('my.xlsx') after I made my changes to the file

Finding Range of active/selected cell in Excel using Python and xlwings

I am trying to write a simple function in Python (with xlwings) that reads a current 'active' cell value in Excel and then writes that cell value to the cell in the next column along from the active cell.
If I specify the cell using an absolute reference, for example range(3, 2), then I everything is ok. However, I can't seem to manage to find the row and column values of whichever cell is selected once the function is run.
I have found a lot of examples where the reference is specified but not where the active cell range can vary depending on the user selection.
I have tried a few ideas. The first option is trying to use the App.selection that I found in the v0.10.0 xlwings documentation but this doesn't seem to return a range reference that can be used - I get an error "Invalid parameter" when trying to retrieve the row from 'cellRange':
def refTest():
import xlwings as xw
wb = xw.Book.caller()
cellRange = xw.App.selection
rowNum = wb.sheets[0].range(cellRange).row
colNum = wb.sheets[0].range(cellRange).column
url = wb.sheets[0].range(rowNum, colNum).value
wb.sheets[0].range(rowNum, colNum + 1).value = url
The second idea was to try to read the row and column directly from the cell selection but this gives me the error "Property object has no attribute 'row'":
def refTest():
import xlwings as xw
wb = xw.Book.caller()
rowNum = xw.App.selection.row
colNum = xw.App.selection.column
url = wb.sheets[0].range(rowNum, colNum).value
wb.sheets[0].range(rowNum, colNum + 1).value = url
Is it possible to pass the range of the active/selected cell from Excel to Python with xlwings? If anyone is able to shed some light on this then I would really appreciate it.
Thanks!
You have to get the app object from the workbook. You'd only use xw.App directly if you wanted to instantiate a new app. Also, selection returns a Range object, so do this:
cellRange = wb.app.selection
rowNum = cellRange.row
colNum = cellRange.column

Why won't this xlsx file open?

I'm trying to use the openpyxl module to take a spreadsheet, see if there are empty cells in a certain column (in this case, column E), and then copy the rows that contain those empty cells to a new spreadsheet. The code runs without traceback, but the resulting file won't open. What's going on?
Here's my code:
#import the openpyxl module
import openpyxl
#First create a new workbook & sheet
newwb = openpyxl.Workbook()
newwb.save('TESTINGTHISTHING.xlsx')
newsheet = newwb.get_sheet_by_name('Sheet')
#open the original file
wb = openpyxl.load_workbook('OriginalWorkbook.xlsx')
#create a sheet object
sheet = wb.get_sheet_by_name('Sheet1')
#Find out how many cells of a certain column are left blank,
#and what rows they're in
count = 0
listofrows = []
for row in range(2, sheet.get_highest_row() + 1):
company = sheet['E' + str(row)].value
if company == None:
listofrows.append(row)
count += 1
print listofrows
print count
#Put the values of the rows with blank company names into the new sheet
for i in range(len(listofrows)):
j = 0
newsheet['A' + str(i+1)] = sheet['A' + str(listofrows[j])].value
j += 1
newwb.save('TESTINGTHISTHING.xlsx')
Please help!
I just ran your program with a mock document. I was able to open my output file without problem. Your issues probably relies within your excel or openpyxl version.
Please provide your software versions in addition to your source document so I can look further into the issue.
You can always update openpyxl with:
c:\Python27\Scripts
pip install openpyxl --upgrade

python: Store all cell values with xlrd and write to new workbook using xlwt

im trying to copy all cells on a sheet to a new workbook. i can store cell values manually like in the example code below and paste variable in respective cells but i want to automate the collection of cell data. I am very new to python but i can conceptually see something along the line of this but i could use some help to finish it, thanks!
attempt to automate cell collection
def cell(r,c):
set r+=1
cellname = c.isalpha() + r
if r <= sheet.nrow:
cellname = (r,c,sheet.cell_value)
...... i get lost around here but i assume there should be a sheet.ncols and nrows
current manual cell copying
cellA1 = sheet.cell_value(0,0)
cellA2 = sheet.cell_value(1,0)
cellA3 = sheet.cell_value(2,0)
cellA4 = sheet.cell_value(3,0)
cellA5 = sheet.cell_value(4,0)
cellB1 = sheet.cell_value(0,1)
cellB2 = sheet.cell_value(1,1)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('ITEM DETAILS')
manual cell pasting
sheet.write(0, 0, cellA1)
sheet.write(1, 0, cellA2)
You can just simply loop through the cells in the sheet, by using sheet.nrows and sheet.ncols as the limit to loop up to. Also, make sure you do not define the new worksheet you are creating as sheet itself, use a new name. Example:
newworkbook = xlwt.Workbook()
newsheet = newworkbook.add_sheet('ITEM DETAILS')
for r in range(sheet.nrows):
for c in range(sheet.ncols):
newsheet.write(r, c, sheet.cell_value(r, c))
Then use newsheet instead of sheet wherever you want to use the new sheet.
Anand S Kumar's answer is correct but you need to change i to r and j to c. For extra benefit I added a bit more code for a complete code example. This code opens an existing excel file, reads all of the data from the first sheet, and writes that same data to a new excel file.
import os,xlrd,xlwt
if os.path.isfile(outExcel):os.remove(outExcel)#delete file if it exists
inExcel= (r'C:\yourpath\inFile.xls')
outExcel= (r'C:\yourpath\outFile.xls')
workbook = xlrd.open_workbook(inExcel)
sheetIn = workbook.sheet_by_index(0)
workbook = xlwt.Workbook()
sheetOut = workbook.add_sheet('DATA')
for r in range(sheetIn.nrows):
for c in range(sheetIn.ncols):
sheetOut.write(r, c, sheetIn.cell_value(r, c))
workbook.save(outExcel)#save the result

Categories

Resources