Python openpyxl not writing to cell - python

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

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

Real-Time Copying and Pasting to Excel

I made this simple program using openpyxl and pyperclip that pastes the clipboard's contents on to successive rows in Excel - so for instance if I copied the word 'hello', it will paste 'hello' on to the cells 'A2, A3, A4...'
However, my main goal is to create a program where I can copy text in real-time and the program pastes it to the cells as so. For example, I copy the text 'hello', the program pastes it onto A2, then I copy the text 'I like python' and it pastes that onto to cell A3 and so on(and then I press a key to end the program when I am done).
Is this possible? If so how can I do this? (I am open to downloading new libraries etc.)
import openpyxl
from openpyxl import Workbook
import pyperclip
wb = Workbook()
column = 'A'
row = 0
# grab the active worksheet
ws = wb.active
#loop through excel rows
for x in range(2,6):
row = x
cell = column + str(row)
ws[cell] = pyperclip.paste()
# Save the file
wb.save("sample.xlsx")
Additional Help: In the case, I (with your help) figure out how to do this, I will also appreciate if someone can tell me how to save the cell number/code too. So for e.g. I run the program and paste the respective text on the the cells 'A1, A2, A3...A14.' Is there a way to also save 'A14' into the memory, so the next time I run the program it starts from A14 and pastes accordingly -'A14, A15, A16...'
import openpyxl
from openpyxl import Workbook
import pyperclip
wb = Workbook()
column = 'A'
row = 0
# grab the active worksheet
ws = wb.active
clipboard = ["quote", "random"]
limit = 10
recentcopy = 'a'
x = 1
while(len(clipboard)<limit):
recentcopy = pyperclip.paste()
if(recentcopy != clipboard [x]):
clipboard.append(pyperclip.paste())
print(clipboard)
row = x + 1
cell = column + str(row)
ws[cell] = clipboard[x]
wb.save("heyo.xlsx")
x = x+1
If you want a simple solution for storing which cell you were at, I'd recommend writing the cell to a text file, then having your program read the text file when it starts so it knows where to continue from. Tutorial for text files with python can be found here: https://www.geeksforgeeks.org/reading-writing-text-files-python/

Python 3x win32com: Copying used cells from worksheets in workbook

I have 6 work sheets in my workbook. I want to copy data (all used cells except the header) from 5 worksheets and paste them into the 1st. Snippet of code that applies:
`
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(mergedXL)
wsSIR = wb.Sheets(1)
sheetList = wb.Sheets
for ws in sheetList:
used = ws.UsedRange
if ws.Name != "1st sheet":
print ("Copying cells from "+ws.Name)
used.Copy()
`
used.Copy() will copy ALL used cells, however I don't want the first row from any of the worksheets. I want to be able to copy from each sheet and paste it into the first blank row in the 1st sheet. So when cells from the first sheet (that is NOT the sheet I want to copy to) are pasted in the 1st sheet, they will be pasted starting in A3. Every subsequent paste needs to happen in the first available blank row. I probably haven't done a great job of explaining this, but would love some help. Haven't worked with win32com a ton.
I also have this code from one of my old scripts, but I don't understand exactly how it's copying stuff and how I can modify it to work for me this time around:
ws.Range(ws.Cells(1,1),ws.Cells(ws.UsedRange.Rows.Count,ws.UsedRange.Columns.Count)).Copy()
wsNew.Paste(wsNew.Cells(wsNew.UsedRange.Rows.Count,1))
If I understand well your problem, I think this code will do the job:
import win32com.client
# create an instance of Excel
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
# Open the workbook
file_name = 'path_to_your\file.xlsx'
wb = excel.Workbooks.Open(file_name)
# Select the first sheet on which you want to write your data from the other sheets
ws_paste = wb.Sheets('Sheet1')
# Loop over all the sheets
for ws in wb.Sheets:
if ws.Name != 'Sheet1': # Not the first sheet
used_range = ws.UsedRange.SpecialCells(11) # 11 = xlCellTypeLastCell from VBA Range.SpecialCells Method
# With used_range.Row and used_range.Col you get the number of row and col in your range
# Copy the Range from the cell A2 to the last row/col
ws.Range("A2", ws.Cells(used_range.Row, used_range.Column)).Copy()
# Get the last row used in your first sheet
# NOTE: +1 to go to the next line to not overlapse
row_copy = ws_paste.UsedRange.SpecialCells(11).Row + 1
# Paste on the first sheet starting the first empty row and column A(1)
ws_paste.Paste(ws_paste.Cells(row_copy, 1))
# Save and close the workbook
wb.Save()
wb.Close()
# Quit excel instance
excel.Quit()
I hope it helps you to understand your old code as well.
Have you considered using pandas?
import pandas as pd
# create list of panda dataframes for each sheet (data starts ar E6
dfs=[pd.read_excel("source.xlsx",sheet_name=n,skiprows=5,usecols="E:J") for n in range(0,4)]
# concatenate the dataframes
df=pd.concat(dfs)
# write the dataframe to another spreadsheet
writer = pd.ExcelWriter('merged.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()

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