Using openpyxl, I am trying to read data from an Excel-Workbook and write data to this same Excel-Workbook. Getting data from the Excel-Workbook works fine, but writing data into the Excel-Workbook does not work. With the code below I get the value from Cell A1 in Sheet1 and print it. Then I try to put some values into the cells A2 and A3. This does not work.
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")
#This works:
print ws1.cell(row=1, column=1).value
#This doesn't work:
ws1['A2'] = "SomeValue1"
#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"
I am sure the code is correct ... What is going wrong here?
I believe you are missing a save function. Try adding the additional line below.
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")
#This works:
print ws1.cell(row=1, column=1).value
#This doesn't work:
ws1['A2'] = "SomeValue1"
#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"
#Add this line
wb.save("testexcel.xlsm")
Use this to write a value:
ws1.cell(row=1, column=1,value='Hey')
On the other hand, the following will read the value:
ws1.cell(row=1, column=1).value
while saving the workbook, try giving the full path.
for example: wb1.save(filename=r"C:\Users\7000027842\Downloads\test.xlsx")
Related
I'm a first time user of openpyxl and am struggling with basic Cell editing.
In the following code I'm trying to change the Cell Value "B3" in my Excel File to a String Value (eg. "Germany").
What I don't seem to understand is why the openpyxl Worksheet & Worbook are an immutable tuple type and the Documentation is suggesting the simple Cell Assignment I'm using.
Here's my Code:
from openpyxl import Workbook
from openpyxl import load_workbook
# 1. Open Excel File
wb = Workbook()
wb = load_workbook(filename="myFile.xlsm", read_only=True, keep_vba=True, data_only=True)
ws = wb.active[1] # ws is the second Worksheet in the Workbook
# 2. Enter Input (Country)
ws["B3"] = "Germany"
wb.save("myFile.xlsm")
ws["B3"] = "Germany"
TypeError: 'tuple' object does not support item assignment
Expectation
I expected to find a Excel file that contains my assigned value in the given cell.
I appreciate every answer - thanks!
Line ws = wb.active[1] is probably wrong. Also you should use read_only=False (simply remove this param, the default is False) if you want to modify the file.
You can assign ws by name. If you don't know the names you can list them like this:
>>> wb.sheetnames
['Sheet1', 'Sheet2', 'Sheet3']
>>> ws = wb['Sheet2'] # or ws = wb.active - "Get the currently active sheet"
>>> ws["B3"] = "Germany"
Whole code:
from openpyxl import Workbook
from openpyxl import load_workbook
# 1. Open Excel File
wb = Workbook()
wb = load_workbook(filename="myFile.xlsm", keep_vba=True, data_only=True)
ws = wb.active # the currently active sheet
# 2. Enter Input (Country)
ws["B3"] = "Germany"
wb.save("myFile.xlsm")
I am new to Python. I want to ask that how to get cell data from excel but not the format?
PICTURE1 this is what I have in the column L34 but PICTURE2 this is the format of the cell. So if now I print the value in
wb = load_workbook('example.xlsx') ws = wb.active print(ws['L34'])
Python it will show the this <Cell 'Sheet1'.L34> but what I want is the 1280.00 for my result. Anyone can help for this? Thank you so much!
Load the excel sheet using the data_only attribute
wb = load_workbook('example.xlsx', data_only=True)
On other option is to calculate each row and get the result. See the sample as following. This will work if your file is a .csv.
The sample excel:
The code to get sum of the each row. You may edit according to your requirement.
import csv
import sys, datetime, time
import re
from openpyxl import load_workbook
import openpyxl
import time
i = 1
with open("test_numbers.csv") as file:
csvreader = csv.reader(file)
for row in csvreader:
row_l = row[0].split(";")
#print(row_l)
if (row_l[0] or row_l[1]).isdigit():
print(f"The result for row{i} = {int(row_l[0])+int(row_l[1])}")
i = i + 1
else:
i = i + 1
The code's output:
Using openpyxl, I am trying to read data from an Excel-Workbook and write data to this same Excel-Workbook. Getting data from the Excel-Workbook works fine, but writing data into the Excel-Workbook does not work. With the code below I get the value from Cell A1 in Sheet1 and print it. Then I try to put some values into the cells A2 and A3. This does not work.
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")
#This works:
print ws1.cell(row=1, column=1).value
#This doesn't work:
ws1['A2'] = "SomeValue1"
#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"
I am sure the code is correct ... What is going wrong here?
I believe you are missing a save function. Try adding the additional line below.
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook("testexcel.xlsm")
ws1 = wb.get_sheet_by_name("Sheet1")
#This works:
print ws1.cell(row=1, column=1).value
#This doesn't work:
ws1['A2'] = "SomeValue1"
#This doesn't work either:
ws1.cell(row=3, column=1).value = "SomeValue2"
#Add this line
wb.save("testexcel.xlsm")
Use this to write a value:
ws1.cell(row=1, column=1,value='Hey')
On the other hand, the following will read the value:
ws1.cell(row=1, column=1).value
while saving the workbook, try giving the full path.
for example: wb1.save(filename=r"C:\Users\7000027842\Downloads\test.xlsx")
This is similar to my earlier question getting formating data in openpyxl The only real difference is that now I really want to use the optimized workbook for the speed increase.
Basically I can't figure out how to retrieve formatting details when I use the optimized reader. Here's a toy sample, the comments explain what I'm seeing on the print statements. Am I doing something wrong? Is there a better way to retrieve formatting details?
Also, if anyone knows of a different excel reader for python that supports xlsx + retrieving formatting I'm open to changing! (I've already tried xlrd, and while that does support xlsx in the newer builds it doesn't yet support formatting)
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
from openpyxl.style import Color, Fill
#this is all setup
wb = Workbook()
dest_filename = 'c:\\temp\\test.xlsx'
ws = wb.worksheets[0]
ws.title = 'test'
ws.cell('A1').value = 'foo'
ws.cell('A1').style.font.bold = True
ws.cell('B1').value = 'bar'
ws.cell('B1').style.fill.fill_type = Fill.FILL_SOLID
ws.cell('B1').style.fill.start_color.index = Color.YELLOW
wb.save(filename = dest_filename )
#setup complete
book = load_workbook( filename = dest_filename, use_iterators = True )
sheet = book.get_sheet_by_name('test')
for row in sheet.iter_rows():
for cell in row:
print cell.coordinate
print cell.internal_value
print cell.style_id #returns different numbers here (1, and 2 in case anyone is interested)
print sheet.get_style(cell.coordinate).font.bold #returns False for both
print sheet.get_style(cell.coordinate).fill.fill_type #returns none for bothe
print sheet.get_style(cell.coordinate).fill.start_color.index #returns FFFFFFFF (white I believe) for both
print
import openpyxl
print openpyxl.__version__ #returns 1.6.2
The style_ID appears to be the index for where you can find the style information in workbook -> shared_styles (book.shared_styles or sheet.parent.shared_styles).
In some workbooks this works flawlessly; but, I've also found in other workbooks the style_ID is greater than the length of shared_styles giving me "Out of range" Exceptions when I try to access said styles.
I need to change the sheet in an excel workbook, as many times as the code runs..Suppose my python scripts runs the first time and data gets saved in sheet A, next time when some application runs my script data should be saved in sheet B.Sheet A should be as it is in that workbook..
Is it posible ? If yes ,How?
Here is my code:
#!/usr/bin/env python
import subprocess
import xlwt
process=subprocess.Popen('Test_Project.exe',stdout=subprocess.PIPE)
out,err = process.communicate()
wb=xlwt.Workbook()
sheet=wb.add_sheet('Sheet_A') #next time it should save in Sheet_B
row = 0
for line in out.split('\n'):
for i,wrd in enumerate(line.split()):
if not wrd.startswith("***"):
print wrd
sheet.write(row,i,wrd)
row=row+1
wb.save('DDS.xls')
Any help is appreciated...
I would recommend using openpyxl. It can read and write xlsx files.
If needed, you can always convert them to xls with Excel or Open/LibreOffice,
assuming you have only one big file at the end.
This script creates a new Excel file if none exists and adds a new sheet every time it is run. I use the index + 1 as the sheet name (title) starting with 1. The numerical index starts at 0. You will end up with a file that has sheets named 1, 2, 3 etc. Every time you write your data into the last sheet.
import os
from openpyxl import Workbook
from openpyxl.reader.excel import load_workbook
file_name = 'test.xlsx'
if os.path.exists(file_name):
wb = load_workbook(file_name)
last_sheet = wb.worksheets[-1]
index = int(last_sheet.title)
ws = wb.create_sheet(index)
ws.title = str(index + 1)
else:
wb = Workbook()
ws = wb.worksheets[0]
ws.title = '1'
ws.cell('A2').value= 'new_value'
wb.save(file_name)