How to unfreeze excel column using python script
wb = load_workbook(excel_file)
ws = wb.active
ws.freeze_panes = None
wb.save(excel_file)
Using above code unfreeze is happening, however If you open processed excel file, the below error is prompted
"we found a problem with some content in excel_file.xlsx. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes"
Use the code below to avoid this error: "we found a problem with
some content in excel_file.xlsx. Do you want us to try to recover as
much as we can? If you trust the source of this workbook, click Yes"
ws - worksheet, wb - workbook
ws.sheet_view.selection = [ws.sheet_view.selection[0]]
ws.sheet_view.selection[0].pane = 'topLeft'
wb.save(excel_file)
Related
I have a very simple spreadsheet with check-marks I want to modify with Python. When I use workbook.save(), the check-marks disappear for some reason.
This is a simplified version of the script I am using, which still reproduces the issue.
from openpyxl import load_workbook
workbook = load_workbook(filename='example.xlsx')
workbook.sheetnames
workbook.active = 0
sheet = workbook.active
sheet
sheet.title
workbook.save(filename="example.xlsx")
This is the spreadsheet before running the script.
This the spreadsheet after running the script.
I have openpyxl 3.0.7 and I don't get any error messages. When I try to install an old version of openpyxl, like pip 3.0.5, and I open the spreadsheet, I get this message.
We found a problem with example.xlsx, we can try to retrieve its content.
I don't know if this information can help.
If you want to open the spreadsheet here you have.
You have to use .xlsm files instead of .xlsx and you have to write:
load_workbook(filename='example.xlsm', read_only=False, keep_vba=True)
instead of:
load_workbook(filename='example.xlsm')
Background:
I am fetching Option chain for a symbol from web and then writing it to an excel sheet. I also have another excel sheet in the same workbook from which I take inputs for the program to run. All of this I am doing with excel 2016.
Sample of the code from program as the whole program is pretty long:
import xlwings as xw
excel_file = 'test.xlsx'
wb = xw.Book(excel_file)
wb.save()
# Fetching User input for Script/Ticker else it will be set to NIFTY as default
try:
Script_Input = pd.read_excel(excel_file, sheet_name = 'Input_Options', usecols = 'C')
script = Script_Input.iloc[0,0]
except:
script = 'NIFTY'
# Writing data in the sheet
sht_name = script + '_OC'
try:
wb.sheets.add(sht_name)
print('new sheet added')
wb.save()
except:
pass
# print('sheet already present')
# directing pointer towards current sheet to be written
sheet = wb.sheets(sht_name)
sheet.range('A4').options(index = False, header = False).value = df
sheet.range('B1').value = underlying
sheet.range('C1').value = underlying_Value
# sheet.range('A3').options(index = False, header = False).value = ce_data_final
# sheet.range('J3').options(index = False, header = False).value = pe_data_final
wb.save()
Problem: Since yesterday, I am able to open my excel workbook with excel 2016 and change inputs for my program but, I do not get any data written in the sheet that takes output from the program. The program runs perfectly as I can test the output on terminal. Also, once I delete the sheet no new sheet is being created as it should.
What I tried: I have uninstalled every other version of excel I had, so now only excel 2016 is present.
I have made sure that all the respective file formats use excel 2016 as the default app.
Also note that, 2 days ago I was able to write data perfectly in the respective sheet but now I am not able to do so.
Any help appreciated...
Sorry to everyone who tried to solve this question.
after #buran asked about 'df' I looked into my code and found that I had a return statement before writing 'df' into sheet (I have created a separate function to write data in excel). Now that I have moved that statement to its proper place the code is working fine. I am extremely sorry as I did not realise what the problem was in the 1st place and assumed it had to do with excel and python. Now the program runs perfectly and I am getting the output I want.
You'll probably laugh at me, but I am sitting on this for two weeks. I'm using python with pandas.
All I want to do, is to put a calculated value in a pre-existing excel file to a specific cell without changing the rest of the file. That's it.
Openpyxl makes my file unusable (means, I can not open because it's "corrupted" or something) or it plainly delets the whole content of the file. Xlsxwriter cannot read or modify pre-existing files. So it has to be pandas.
And for some reason I can't use worksheet = writer.sheets['Sheet1'], because that leads to an "unhandled exception".
Guys. Help.
I tried a bunch of packages but (for a lot of reasons) I ended up using xlwings. You can do pretty much anything with it in python that you can do in Excel.
Documentation link
So with xlwings you'd have:
import xlwings as xw
# open app_excel
app_excel = xw.App(visible = False)
# open excel template
wbk = xw.Book( r'stuff.xlsx' )
# write to a cell
wbk.sheets['Sheet1'].range('B5').value = 15
# save in the same place with the same name or not
wbk.save()
wbk.save( r'things.xlsx' )
# kill the app_excel
app_excel.kill()
del app_excel
Let me know how it goes.
I'm creating a small app in Django that produces a Excel report using openpyxl library. Got stuck while trying to insert an image in the header / footer section. The documentation here roughly talks about inserting text (& ampersand codes). Checked the source code, but no help there either.
I see XlsxWriter has this option. Would appreciate if someone could shed me light on how to pass image's name/path in openxlpy or do I need to switch the library?
View.py
def get(self, request):
wb = Workbook()
ws = wb.active
# header & footer
ws.header_footer.center_header.text = '&G'
This is currently not possible in openpyxl, and unlikely ever to be so unless someone else contributes the code. Therefore, you may have to switch to using xlsxwriter.
NB. adding it would also involve preserving images from existing files, which is one of the things that makes this so challenging. We open to add general support for reading images in openpyxl 2.5
In openpyxl you can add an image (inserted into some_cell) to a worksheet by doing the following:
wb = openpyxl.Workbook()
ws = wb.add_worksheet() #or wb.active
your_image = openpyxl.drawing.Image(path_to_image)
your_image.anchor(ws.cell(some_cell))
ws.add_image(your_image)
wb.save(your_filename.xlsx)
Let me preface this by saying I have tried looking for, and cannot seem to find a similar situation so please don't be too upset if this seems familiar to you. I am using Python 2.7 and openpyxl version 2.2.5 (I need to use 2.7, and used an older module for other reasons.)
I am new to Python and read/write code in general, so I'm testing this on the command line before I implement it:
I created a file, foo.xlsx in the Python27 file directory with some values that I manually entered via Excel.
I then used this simple code on the Python command line to test my code
from openpyxl import load_workbook
wb = load_workbook('foo.xlsx')
sheet_ranges = wb['range names']
It then resulted in the following error:
File "C:\Python27\lib\openpyxl\workbook.workbook.py", line 233 in getitem
raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet sheet range names does not exist'
So I thought it had something to do with not importing the entire openpyxl module. I proceeded to do that and run the whole process but it resulted in the same error.
Can someone please let me know what I am doing wrong/how to solve this?
Additional information:
I had successfully written to an empty file before, and then read the values. This gave me the right values for everything EXCEPT what I had written in manually via Excel- the cells that had manual input returned None or Nonetype. The issue seems to be with cells with manual input.
I did hit save on the file before accessing it don't worry
This was in the same directory so I know that it wasn't a matter of location.
The following command does not make sense:
sheet_ranges = wb['range names']
Normally you open a workbook and then access one of the worksheets, the following gives you some examples on how this can be done:
import openpyxl
wb = openpyxl.Workbook()
wb = openpyxl.load_workbook(filename = 'input.xlsx')
# To display all of the available worksheet names
sheets = wb.sheetnames
print sheets
# To work with the first sheet (by name)
ws = wb[sheets[0]]
print ws['A1'].value
# To work with the active sheet
ws = wb.active
print ws['A1'].value
# To work with the active sheet (alternative method)
ws = wb.get_active_sheet()
print ws['A1'].value
If you want to display any named range in the workbook, you can do the following:
print wb.get_named_ranges()
I'm not exactly sure what it is you need to do, but to read Excel spreadsheets into python, I usually use xlrd (which to me was easier to get use to). See example:
import xlrd
workbook = xlrd.open_workbook(in_fname)
worksheet = workbook.sheet_by_index(0)
To write to Excel spreadsheets, I use xlsxwriter:
import xlsxwriter
workbook = xlsxwriter.Workbook(out_fname)
worksheet = workbook.add_worksheet('spreadsheet_name')
Hope this helps.