Sorry for my English. I need to open a xlsx document and write in the last position new values. But I don't understand how to do it. My algorithm works like this:
Open xlsx l_workbook = load_workbook(old_log_tmp_path)
Get all value from there
Code:
def iter_rows(ws):
for row in ws.iter_rows():
yield [cell for cell in row]
Create new xlsm file
Code:
workbook = xlsxwriter.Workbook(tf.name)
worksheet = workbook.add_worksheet()
Copy all values from l_workbook to workbook -> worksheet
But I think it is not right, I think they exist in a simple way. Like this:
l_workbook = load_workbook('EX2cRqM7xi1D.xlsx')
sheet = l_workbook.get_sheet_names()[0]
worksheet = l_workbook.get_sheet_by_name(sheet)
worksheet.write(1, 1, "TEST")
Running that script gave me the error below:
AttributeError: 'Worksheet' object has no attribute 'write'
My question is: How can I open xlsm file and add new values to it (using openpyxl)?
UPD:
i try this code, but not work
import openpyxl
workbook = openpyxl.load_workbook('tmp3by148hj.xlsx')
ws = workbook.worksheets[0]
ws.cell(row=1, column=1).value = 'TEST'
You need to write into a cell:
worksheet.cell(row=1, column=1).value = 'TEST'
and finally save your changes:
workbook.save('tmp3by148hj.xlsx')
Related
I'm attempting to write to a cell using openpyxl, but am getting error "Worksheet Sheet1 does not exist."
def CreateWorkbook(workbook_path):
workbook = openpyxl.Workbook()
workbook.save(workbook_path)
return workbook_path
def CreateSheet(workbook, sheet_name):
workbook.create_sheet(sheet_name)
workbook.save(workbook_path)
return sheet_name
def WriteCell(workbook, sheet_name, cell, cell_data):
worksheet = workbook[sheet_name]
worksheet[cell] = cell_data
return
workbook = CreateWorkbook('workbook1.xlsx')
sheet = CreateSheet(workbook, 'Sheet1')
WriteCell(workbook, sheet, 'A1', 'testing')
This code isn't really good and has multiple errors. For example, in CreateWorkbook, you create a workbook, and then save it. However, after, in CreateSheet, you don't actually, reopen the file. The file must be re opened after every save. This is how I would fix those errors:
import openpyxl
def CreateWorkbook(workbook_path):
workbook = openpyxl.Workbook()
workbook.save(workbook_path)
return workbook_path
def CreateSheet(workbook, sheet_name):
wb = openpyxl.load_workbook(workbook)
wb.create_sheet(sheet_name)
wb.save(workbook)
return sheet_name
def WriteCell(workbook, sheet_name, cell, cell_data):
wb = openpyxl.load_workbook(workbook)
worksheet = wb[sheet_name]
worksheet[cell] = cell_data
wb.save(workbook)
return
workbook = CreateWorkbook('workbook1.xlsx')
sheet = CreateSheet(workbook, 'Sheet1')
WriteCell(workbook, sheet, 'A1', 'testing')
Maybe you should post the complete class code, there are some things that don't really make sense like for instance in:
def CreateSheet(workbook, sheet_name):
workbook.create_sheet(sheet_name)
workbook.save(workbook_path)
return sheet_name
when you return sheet_name - this is basically the same value as you give in the input, it's pointless. Secondly, you use workbook_path as a parameter, I assume it's a class attribute, otherwise it's not clear how you have it in the method.
Also in:
def CreateWorkbook(workbook_path):
workbook = openpyxl.Workbook()
workbook.save(workbook_path)
return workbook_path
you return the same input argument workbook_path which again dosn't make sense and in the code below you use the workbook_path as workbook. This here might be the error, but there are a few so might be also sth else.
For your problem try to debug the code, eventually print out at every method a "proof" that the object created was actually created.
I am trying to add a DataFrame to rows below existing cells on an existing .xlsx file with this code:
book = load_workbook(r"C:\path\file_name.xlsx")
writer = pd.ExcelWriter(r"C:\path\file_name.xlsx", engine='openpyxl')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}
contract_df.to_excel(writer, startrow = 10, header = False,
sheet_name='UsrLeaseContract')
writer.save()
I manage to add the data, but I am getting the following error when re-opening the file:
Removed Part: /xl/styles.xml part with XML error. (Styles) HRESULT
0x8000ffff Line 1, column 0. Repaired Records: Cell information from
/xl/worksheets/sheet1.xml part
and the detailed XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error344800_01.xml </logFileName>
<summary>
Errors were detected in file 'C:path\file_name.xlsx'
</summary>
<removedParts><removedPart>Removed Part: /xl/styles.xml part with XML error. (Styles) HRESULT 0x8000ffff Line 1, column 0.
</removedPart>
</removedParts><repairedRecords><repairedRecord>Repaired Records: Cell information from /xl/worksheets/sheet1.xml part</repairedRecord>
</repairedRecords></recoveryLog>
Have you tried using openpyxl directly to append the data?
Ran this code and it ran without problems. Also, did not get any warnings when opening the Exel file.
from openpyxl import Workbook, load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
# list of strings
vegetables = ['potatoes', 'carrots', 'cabbage']
# Calling DataFrame constructor on list
df = pd.DataFrame(vegetables)
wb = load_workbook('file_name.xlsx')
ws = wb['UsrLeaseContract']
for r in dataframe_to_rows(df, index=True, header=True):
ws.append(r)
wb.save('file_name.xlsx')
All I want to do is copy a worksheet from an excel workbook to another excel workbook in Python.
I want to maintain all formatting (coloured cells, tables etc.)
I have a number of excel files and I want to copy the first sheet from all of them into one workbook. I also want to be able to update the main workbook if changes are made to any of the individual workbooks.
It's a code block that will run every few hours and update the master spreadsheet.
I've tried pandas, but it doesn't maintain formatting and tables.
I've tried openpyxl to no avail
I thought xlwings code below would work:
import xlwings as xw
wb = xw.Book('individual_files\\file1.xlsx')
sht = wb.sheets[0]
new_wb = xw.Book('Master Spreadsheet.xlsx')
new_wb.sheets["Sheet1"] = sht
But I just get the error:
----> 4 new_wb.sheets["Sheet1"] = sht
AttributeError: __setitem__
"file1.xlsx" above is an example first excel file.
"Master Spreadsheet.xlsx" is my master spreadsheet with all individual files.
In the end I did this:
def copyExcelSheet(sheetName):
read_from = load_workbook(item)
#open(destination, 'wb').write(open(source, 'rb').read())
read_sheet = read_from.active
write_to = load_workbook("Master file.xlsx")
write_sheet = write_to[sheetName]
for row in read_sheet.rows:
for cell in row:
new_cell = write_sheet.cell(row=cell.row, column=cell.column,
value= cell.value)
write_sheet.column_dimensions[get_column_letter(cell.column)].width = read_sheet.column_dimensions[get_column_letter(cell.column)].width
if cell.has_style:
new_cell.font = copy(cell.font)
new_cell.border = copy(cell.border)
new_cell.fill = copy(cell.fill)
new_cell.number_format = copy(cell.number_format)
new_cell.protection = copy(cell.protection)
new_cell.alignment = copy(cell.alignment)
write_sheet.merge_cells('C8:G8')
write_sheet.merge_cells('K8:P8')
write_sheet.merge_cells('R8:S8')
write_sheet.add_table(newTable("table1","C10:G76","TableStyleLight8"))
write_sheet.add_table(newTable("table2","K10:P59","TableStyleLight9"))
write_to.save('Master file.xlsx')
read_from.close
With this to check if the sheet already exists:
#checks if sheet already exists and updates sheet if it does.
def checkExists(sheetName):
book = load_workbook("Master file.xlsx") # open an Excel file and return a workbook
if sheetName in book.sheetnames:
print ("Removing sheet",sheetName)
del book[sheetName]
else:
print ("No sheet ",sheetName," found, will create sheet")
book.create_sheet(sheetName)
book.save('Master file.xlsx')
with this to create new tables:
def newTable(tableName,ref,styleName):
tableName = tableName + ''.join(random.choices(string.ascii_uppercase + string.digits + string.ascii_lowercase, k=15))
tab = Table(displayName=tableName, ref=ref)
# Add a default style with striped rows and banded columns
tab.tableStyleInfo = TableStyleInfo(name=styleName, showFirstColumn=False,showLastColumn=False, showRowStripes=True, showColumnStripes=True)
return tab
Adapted from this solution, but note that in my (limited) testing (and as observed in the other Q&A), this does not support the After parameter of the Copy method, only Before. If you try to use After, it creates a new workbook instead.
import xlwings as xw
wb = xw.Book('individual_files\\file1.xlsx')
sht = wb.sheets[0]
new_wb = xw.Book('Master Spreadsheet.xlsx')
# copy this sheet into the new_wb *before* Sheet1:
sht.api.Copy(Before=new_wb.sheets['Sheet1'].api)
# now, remove Sheet1 from new_wb
new_wb.sheets['Sheet1'].delete()
This can be done using pywin32 directly. The Before or After parameter needs to be provided (see the api docs), and the parameter needs to be a worksheet <object>, not simply a worksheet Name or index value. So, for example, to add it to the end of an existing workbook:
def copy_sheet_within_excel_file(excel_filename, sheet_name_or_number_to_copy):
excel_app = win32com_client.gencache.EnsureDispatch('Excel.Application')
wb = excel_app.Workbooks.Open(excel_filename)
wb.Worksheets[sheet_name_or_number_to_copy].Copy(After=wb.Worksheets[wb.Worksheets.Count])
new_ws = wb.ActiveSheet
return new_ws
As most of my code runs on end-user machines, I don't like to make assumptions whether Excel is open or not so my code determines if Excel is already open (see GetActiveObject), as in:
try:
excel_app = win32com_client.GetActiveObject('Excel.Application')
except com_error:
excel_app = win32com_client.gencache.EnsureDispatch('Excel.Application')
And then I also check to see if the workbook is already loaded (see Workbook.FullName). Iterate through the Application.Workbooks testing the FullName to see if the file is already open. If so, grab that wb as your wb handle.
You might find this helpful for digging around the available Excel APIs directly from pywin32:
def show_python_interface_modules():
os.startfile(os.path.dirname(win32com_client.gencache.GetModuleForProgID('Excel.Application').__file__))
I generate an xlsx file with lots of sheets and I want to take me at specific position when I open it manually with Excel. This function does the job but for one sheet only. How can I apply it to all of the sheets in workbook?
import win32com.client
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files\1.xlsx')
ws = xl.ActiveSheet
ws.Range('B100').Select()
wb.Close(True)
xl.Quit()
select_cell()
I want to make something like this:
import win32com.client
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files\1.xlsx')
for ws in wb.Worksheets():
ws.Range('B100').Select()
wb.Close(True)
xl.Quit()
select_cell()
In order to be taken to specific cell in newly generated document it is necessary to have both of these expressions executed:
ws.Range('k100').Value = 1
ws.Range('k100').Select()
To do it in every sheet of the workbook:
def select_cell():
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open(r'H:\Files1.xlsx')
for sh in wb.Sheets:
xl.Worksheets(sh.Name).Activate()
ws = xl.ActiveSheet
ws.Range('k100').Value = 1
ws.Range('k100').Select()
wb.Close(True)
xl.Quit()
The code above will take you to K100 on every worksheet in the book.
Your script did nothing at all when I tested it.
The script below worked fine, based on my test.
import xlsxwriter
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:\\Users\\Excel\\Desktop\\book1.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})
# Write some simple text.
worksheet.write('A1', 'Hello')
# Text with formatting.
worksheet.write('A2', 'World', bold)
# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
workbook.close()
I have the following iteration:
for key, df in dictHistory.items():
wb = Workbook(file_path)
Range(key, "A1").value = df
wb.save()
wb.close()
Where dictHistory is of type <String,pd.DataFrame>, so to speak.
The file exists, and the sheet exists in the file.
Yet when running I am getting the following error:
NameError: You must first instantiate a Workbook object.
And
xlwings.__version__
yields:
'0.3.2'