OpenPyXL - Header/Footer - Can't write header to sheet - python

I'm trying to write a header to a spreadsheet I've created for work. I have followed the openpyxl docs as precisely as I can. However, it still won't give me a header. Here is a simple example (almost exactly as the docs) that will not work for me:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
ws.oddHeader.text = "fffffffffffffffffff"
ws.oddHeader.size = 14
ws.oddHeader.font = "Tahoma,Bold"
ws.oddHeader.color = "CC3366"
ws.cell(row=1, column=1).value = 'hello'
wb.save('C:/Users/ffffffff/Desktop/test.xlsx')
Docs: http://openpyxl.readthedocs.io/en/default/print_settings.html

I've looked at this in more detail and the problem is in the openpyxl documentation. Headers and footers have three areas: left, centre/center and right and at least one of these must be used.
Your code only needs to be changed slightly to work:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.oddHeader.center.text = "fffffffffffffffffff"
ws.oddHeader.center.size = 14
ws.oddHeader.center.font = "Tahoma,Bold"
ws.oddHeader.center.color = "CC3366"
ws.cell(row=1, column=1).value = 'hello'
wb.save('test.xlsx')

Related

Python (OpenPyxl) openpyxl not write anything

Code :
wb = Workbook()
sdwbb = load_workbook(sdpath)
filename = os.path.basename(sdpath)
bulan = "September"
try:
sdp = sdwbb[bulan]
except:
sdwbb.create_sheet(bulan)
wb.save(filename)
time.sleep(0.5)
sdp = sdwbb[bulan]
cell_one = sdp['F1']
cell_one.value = 'test'
sdwbb.save(filename)
for your information I doesn't get any error but its doesn't write anything cell f1 sheet September
what I trying to do is to write on specific workbook ,sheet ,and cell
This is my code to write "test" in cel F1 (in the current sheet) in the file test.xlxs in the same folder:
from openpyxl import Workbook, load_workbook
wb = load_workbook("test.xlsx")
ws = wb.active
ws["F1"] = "test"
wb.save("test.xlsx")
print("done")
It's as easy as that :).
Also, you should devenitly check out the documentation of openpyxl: https://openpyxl.readthedocs.io/en/stable/tutorial.html#create-a-workbook

Copy pasting multiple sheets into new workbook

The goal is to copy paste multiple existing sheets out of a workbook into a new workbook using xlwings. I have:
app = xw.App(visible=False)
book = xw.Book(path)
sheet_1 = book.sheets["Sheet1"]
sheet_2 = book.sheets["Sheet2"]
wb_res = xw.Book()
sheet_active = wb_res.sheets.active
sheet_1.api.Copy(Before=sheet_active)
This throws:
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
Bonus question for the brave:
- How can I replace all formulas on a sheet for its value?
Thanks
If you can use win32com, you can try this:
from win32com.client import Dispatch
path1 = 'workbook1.xlsx'
path2 = 'workbook2.xlsx'
xl = Dispatch("Excel.Application")
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()

How can I still use functions in excel and print their output ( and not the function) to my python prog.?

This is the code I'm using but, If I use a function in excel, python prints only the function and not it's output. I imagine this is normally fixed using an intermediary like notebook, but the Arabic typeface does not transfer over. Any help you could give would be greatly appreciated.
Thanks,
William M. Hollingsworth
rom openpyxl import load_workbook
def main():
wb = load_workbook(filename ="F:\\Quran Gematria.xlsx", read_only=True)
ws = wb['Sheet1']
bigdict = {}
rowcount = 0
for row in ws.rows:
rowdict = {}
rowdict['words'] = row[0].value
rowdict['sum'] = row[1].value
rowdict['prime']=row[2].value
rowdict['form'] = row[3].value
rowdict['verse'] = row[4].value
bigdict[rowcount] = rowdict
rowcount += 1
for wordkey in bigdict:
if(bigdict[wordkey]['form'] ==74):
print(bigdict[wordkey])
main()
set data_only to True when load workbook:
import openpyxl
wb = openpyxl.load_workbook('forecast.xlsx', data_only=True)

Openpyxl - how to populate data on specific sheet

I'm using openpyxl for the first time. I have to read excel file, then after manipulation, populate the result on three different excel sheets -> sheet_T, sheet_D and sheet_U. I created three sheets using openpyxl as follows-
sheet_T = filename2.create_sheet(0)
sheet_T.title = "Target First"
sheet_D = filename2.create_sheet(1)
sheet_D.title = "Distractor First"
sheet_U = filename2.create_sheet(2)
sheet_U.title = "Unclassified"
I used xlwt to do it but there is a constraint of 256 columns. Hence, I used openpyxl. The below code is written by using xlwt-
sheet_T.write(row_first, col_target, Name_Target)
sheet_D.write(row_first, col_target, Name_Target)
sheet_U.write(row_first, col_target, Name_Target)
How do I write the same thing by using openpyxl? All the documentation I read is how to write on a specific cell not sheet.
Many thanks for the help!
You need to create another sheet:
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
wb = Workbook()
ws0 = wb.worksheets[0]
ws0.title = 'My Sheet 1'
ws1 = wb.create_sheet()
ws1.title = 'My Sheet 2'
ws2 = wb.create_sheet()
ws2.title = 'My Sheet 3'
Now you can write to the different sheets:
cell_ws0_a1 = ws0.cell('A1')
cell_ws0_a1.value = 'Wrote to cell in 1st sheet.'
cell_ws1_a1 = ws1.cell('A1')
cell_ws1_a1.value = 'Wrote to cell in 2nd sheet.'
cell_ws2_a1 = ws2.cell('A1')
cell_ws2_a1.value = 'Wrote to cell in 3rd sheet.'
writer = ExcelWriter(workbook=wb)
writer.save('example.xlsx')
There is only one sheet in a workbook by default. wb.create_sheet() creates a second sheet.
I would like to make a correction in the code for smooth running-
from openpyxl.workbook import Workbook
from openpyxl.writer.excel import ExcelWriter
wb = Workbook()
ws0 = wb.worksheets[0]
ws0.title = 'My Sheet 1'
ws1 = wb.create_sheet()
ws1.title = 'My Sheet 2'
ws2 = wb.create_sheet()
ws2.title = 'My Sheet 3
v1 = ws1.cell(row=1, column=1)
v1.value = "Hello"
(Basically insert values in this manner instead)
And then end with-
writer = ExcelWriter(wb, 'file.xlsx')
wb.save('file.xlsx')
Hope this helps :)

Activate second worksheet with openpyxl

I am trying to activate multiple excel worksheets and write to both multiple sheets within both workbook(s) using python and openpyxl. I am able to load the second workbook f but I am unable to append cell G2 of my second workbook with the string Recon
from openpyxl import Workbook, load_workbook
filename = 'sda_2015.xlsx'
wb = Workbook()
ws = wb.active
ws['G1'] = 'Path'
ws.title = 'Main'
adf = "Dirty Securities 04222015.xlsx"
f = "F:\\ana\\xlmacro\\" + adf
wb2 = load_workbook(f)
"""
wb22 = Workbook(wb2)
ws = wb22.active
ws['G1'] = "Recon2"
ws.title = 'Main2'
"""
print wb2.get_sheet_names()
wb.save(filename)
I commented out the code which is broken
Update
I adjusted my code with the below answer. The value in cell H1 is written onto wb2 in column H, but for some reason the column is hidden. I have adjusted the column to other columns but still I have seen the code hide multiple columns. There are also occurences when the code executes and titles ws2 as Main21 but the encoded value is Main2
from openpyxl import Workbook, load_workbook
filename = 'sda_2015.xlsx'
wb1 = Workbook()
ws1 = wb1.active
ws1['G1'] = 'Path'
ws1.title = 'Main'
adf = "Dirty Securities 04222015.xlsx"
f = "F:\\ana\\xlmacro\\" + adf
wb2 = load_workbook(f)
ws2 = wb2.active
ws2['H1'] = 'Recon2'
ws2.title = 'Main2'
print wb2.get_sheet_names()
wb1.save(filename)
wb2.save(f)
If you have two workbooks open, wb1 and wb2, you'll also need different names for the various worksheets: ws1 = wb1.active and ws2 = wb2.active.
If you're working with a file with macros, you'll need to set the keep_vba flag to True when opening it in order to preserve the macros.
I had experienced the same thing with hidden cells. Eventually, I unpacked the Excel file and looked at the raw XML to find out that not all of the columns had a dimension for width. Those without a width were being by Excel.
A quick fix is to do something like this...
for col in 'ABCDEFG':
if not worksheet.column_dimensions[col].width:
worksheet.column_dimensions[col].width = 10

Categories