I'm using formulas:
wsheet.write(i, j, Formula('HYPERLINK(%s;"Link")' % click), docnm)
in my Excel files
and when it first opens up it goes into "Protected View". My formulas don't load until after I click "Enable Editing". Is there anyway to get my numbers to show up even if Protected Mode is on?
I found a similar topic on this link Protected View in Microsoft Excel 2010 and Python , but there aren't any useful answers..
Can someone help me please?
Complete code:
from xlwt import easyxf,Formula
import xlwt
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet("MySheet")
wsheet.col(j).width = 17000
link="https://stackoverflow.com/"
click="http://ccwebviewer.ac.de.eu.ericsson.se/~"+excelbranch+link
click='"'+str(click)+'"'
linkName='"'+"LINK"+'"'
wsheet.write(1, 1, Formula('HYPERLINK(%s;%s)' % (click,linkName)))
wbook.save("excel.xls")
I have tried a basic example with the code below and seem to be able to open the workbook produced without a prompt and follow the link:
import xlwt
link_url = 'http://stackoverflow.com/questions/21430921/disable-protected-view-mode-in-excel-files-with-xlwt-python' #'file1.csv'
outputfile = 'outputList.xls'
wbk = xlwt.Workbook()
wsheet = wbk.add_sheet('sheet 1')
xlformula = 'HYPERLINK("'+link_url+'", "Link")'
wsheet.write(0, 0, xlwt.ExcelFormula.Formula(xlformula))
wbk.save(outputfile)
This basically creates a new workbook and writes a link to the URL for this question and saves the workbook.
Related
I have been asked to create a web page with django, with a button in it, which when clicked runs a python script in command prompt in your system. It updates an excel file, from which data is to be extracted and updated to another excel which will be available in microsoft sharepoint. The file with the required python and excel files is given and are not to be disturbed.
I have created the web page in django and and the button as well. I have also written a python script which extracts the data and updates in the other excel file which is as follows
import pandas as pd
import openpyxl as op
def xl():
A = pd.read_excel('testcase_database.xlsx') #The excel file from which the data is to be taken
B = pd.read_excel('S32K3XX_SecureBAF_Sprint3_Test_Report.xlsx', sheet_name='Test_Report') #The excel file to which the data is to be updated
tcname = A['Unnamed: 2']#Test case nams in A
fcname = B['Unnamed: 5'] #Test case names in B
pi = A['Unnamed: 5'] #Results in A
temp = ""
temp1 = ""
#To compare the test case names in A and B and then printing that test case result in B
for i, temp in enumerate(tcname):
for j, temp1 in enumerate(fcname):
if temp == temp1:
B['Unnamed: 15'].iat[j] = pi[i]
else:
continue
pf = B['Unnamed: 15'].tolist() #Results in B
wb = op.load_workbook('S32K3XX_SecureBAF_Sprint3_Test_Report.xlsx')
ws=wb.active
for i in range(1,512):
c = ws.cell(row=i,column=16)
j = i-1
c.value = pf[j]
wb.save('Sprint3_Test_Report.xlsx')
return xl
But i am having problem with running the python script in the cmd when the button is clicked , and not sure on how to deploy it in a web page which can be accesed by anyone, and where do I host the folder containing the python and excel files for the webpage to access and update them, and how to make them accessible via sharepoint?
To run the script, make it a django view:
from django.http import HttpResponse
from openpyxl import Workbook
def export_excel(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = f'attachment; filename="filename.xls"'
wb = Workbook()
...
wb.save(response)
return response
The function above makes your browser download the generated excel file.
I don't know about the microsoft sharepoint part, but that's a start.
I am trying to print Excel files to pdf with xlwings. I am using the excel api for this.
I have tried it in two ways:
1/ Using the PrintOut() call with PrintToFile argument:
wb.api.PrintOut(PrintToFile=True, PrToFileName="5.pdf", Preview=True)
The problem here is Excel just prints the file, ignoring my additional settings.
2/ Using ExportAsFixedFormat
wb.api.ExportAsFixedFormat(0, str(SwmId) + ".pdf")
Here Excel flashes a bit, but does not do anything in the end.
For the record: I can't use a macro and call it from Python because I have about a thousand of these Excel files. So, I can't put the macro in every single one of them. It would probably be a workaround to create a custom function in VBA and than call it every file. But, honestly, it would be easier if I could just do this directly from Python, in one line of code.
Below is a self-standing code example of what worked on my machine to print an excel workbook to pdf (using the ExportAsFixedFormat method):
# Environment
# -----------
# OS: Windows 10
# Excel: 2013
# python: 3.7.4
# xlwings: 0.15.8
import os
import xlwings as xw
# Initialize new excel workbook
book = xw.Book()
sheet = book.sheets[0]
sheet.range("A1").value = "dolphins"
# Construct path for pdf file
current_work_dir = os.getcwd()
pdf_path = os.path.join(current_work_dir, "workbook_printout.pdf")
# Save excel workbook to pdf file
print(f"Saving workbook as '{pdf_path}' ...")
book.api.ExportAsFixedFormat(0, pdf_path)
# Open the created pdf file
print(f"Opening pdf file with default application ...")
os.startfile(pdf_path)
xlwings documentation recommends using xw.App():
from pathlib import Path
import xlwings as xw
import os
with xw.App() as app:
# user will not even see the excel opening up
app.visible = False
book = app.books.open(path_to_excelfile)
sheet = book.sheets[0]
sheet.page_setup.print_area = '$A$1:$Q$66'
sheet.range("A1").value = "experimental"
# Construct path for pdf file
current_work_dir = os.getcwd()
pdf_file_name = "pdf_workbook_printout.pdf"
pdf_path = Path(current_work_dir, pdf_file_name)
# Save excel workbook as pdf and showing it
sheet.to_pdf(path=pdf_path, show=True)
i have a weekly report that i need to do, i chooseed to create it with openpyxl python module, and send it via mail, when i open the received mail (outlook), the cells with formulas appears as empty, but when downloading the file and open it, the data appears, OS fedora 20. parts of the code :
# imported modules from openpyxl ...
wb = Workbook()
ws = wb.active
counter = 3
ws.append(row)
for day in data :
row = ['']*(len(hosts)*2 +5)
row[0] = day.dayDate
row[1] ='=SUM(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+\
')/(COUNT(F'+str(counter)+':'+get_column_letter(len(hosts)+5)+str(counter)+'))'
row[2] = '=SUM('+get_column_letter(len(hosts)+6)+str(counter)+':'+\
get_column_letter(len(hosts)*2+5)+str(counter)+')/COUNT('+\
get_column_letter(len(hosts)+6)+str(counter)+':'+\
get_column_letter(len(hosts)*2+5)+str(counter)+')'
row[3] = '=MAX('+get_column_letter(len(hosts)+6)+str(counter)+':'+\
get_column_letter(len(hosts)*2+5)+str(counter)+')'
row[4] = '=_xlfn.STDEV.P('+get_column_letter(len(hosts)+6)+str(counter)\
+':'+get_column_letter(len(hosts)*2+5)+str(counter)+')'
counter += 1
then, i create from the date some charts, etc.. and save, then send via mail :
wb.save(pathToFile+fileName+'.xlsx')
os.system('echo -e "'+msg+'" | mail -s "'+fileName+'" -a '+\
pathToFile+fileName+'.xlsx -r '+myUsr+' '+ppl2send2)
those are parts of the actual code, any one have an idea why the email don't show the results of the formulas in the cells ? Thanks in advance :)
openpyxl doesn't compute a result for formulas inserted into a spreadsheet; if you open the sheet with excel and save it, the result will have values filled in.
opepyxl has a problem with formulas, after you update your excel file you need to open it and save it to get the values generated. There are two ways to solve this problem.
(I won't advice you to use this unless you really want it.)
You can automate the process of opening the file and saving it from python before reading it. You can do this by using the win32com module
import win32com.client
wb.save('PUT YOUR FILE PATH HERE')
ab = win32com.client.Dispatch("Excel.Application")
wb2 = ab.Workbooks.Open('PUT YOUR FILE PATH HERE')
ws = ab.Sheets('PUT THE SHEET NAME HERE')
ab.DisplayAlerts = False
wb2.Save()
wb2.Close()
ab.Application.Quit()
#Now you can read from the file and you can see the values generated from the formula
Or you can use xlwings instead of openpyxl. if you use this module you don't have to worry about saving the excel file. The module will do it for you.
import xlwings
wb= xlwings.Book('PUT YOUR FILE PATH HERE')
ws = wb.sheets[0]
#Do your update here example ws.range(2, 8).value = 34
wb.save()
wb.close()
I need to write a code to tell Python to look into an excel sheet, extract a table and paste it as an image on an email. Thus far, I have managed to tell Python to write web content onto that excel file from a website and even send out an email. The gap is really lies in the step described in the first sentence above. The whole idea of this project is really not needing to open the excel file at all and running everything via Python.
Been spending quite abit of time on this but the best result so far is only one where Python can print cell data from excel but no the entire table as an image.
Really appreciate some help here. Thank you and cheers.
Code attached:
import requests
response = requests.get("")
txt=response.text
lines = txt.split('\n')
print(lines[25])
from openpyxl import load_workbook
wb = load_workbook(filename = 'abc.xlsm', read_only=False, keep_vba=True)
ws1 = wb['Sheet1']
ws1['A2'].value = (lines[25])
wb.save('abc.xlsm')
# Up to this point I have managed to get Python to extract web content and write into an existing excel file.
import win32com.client
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "My Subject"
newMail.Body = "My Body"
newMail.To = "..."
newMail.Send()
#This sends out the email. This tries to get Python to print out the entire sheet but it comes out quite jumbled:
import xlrd
book = xlrd.open_workbook('C:/Users/adriel.cheng/Desktop/Inspection Sales_v8.xlsm')
print (book.nsheets)
print (book.sheet_names())
#An alternative approac but it also comes out jumbled:
import pandas as pd
xl = pd.ExcelFile('C:/Users/adriel.cheng/Desktop/Inspection Sales_v8.xlsm')
xl.sheet_names
df = xl.parse("Inspections sheet")
print (df)
I tried to search many places but dit not see any example snippet of code about how to delete an existing worksheet in excel file by using xlutils or xlwt with python. Who can help me, please?
I just dealt with this and although this is not generally a good coding choice, you can use the internal Workbook_worksheets to access and set the worksheets for a workbook object.
write_book._Workbook__worksheets = [write_book._Workbook__worksheets[0]]
this would strip everything but the first worksheet associated with a Workbook
I just wanted to confirm that I got this to work using the answer David gave. Here is an example of where I had a spreadsheet (workbook) with 40+ sheets that needed to be split into their own workbooks. I copied the master workbook removed all but the one sheet and saved to a new spreadsheet:
from xlrd import open_workbook
from xlutils import copy
workbook = open_workbook(filepath)
# Process each sheet
for sheet in workbook.sheets():
# Make a copy of the master worksheet
new_workbook = copy.copy(workbook)
# for each time we copy the master workbook, remove all sheets except
# for the curren sheet (as defined by sheet.name)
new_workbook._Workbook__worksheets = [ worksheet for worksheet in new_workbook._Workbook__worksheets if worksheet.name == sheet.name ]
# Save the new_workbook based on sheet.name
new_workbook.save('{}_workbook.xls'.format(sheet.name))
The following method does what you need:
def deleteAllSheetBut(workingFolder, xlsxFILE, sheetNumberNotToDelete=1):
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open( os.path.join( workingFolder, xlsxFILE ) )
for i in range(1, wb.Worksheets.Count):
if i != sheetNumberNotToDelete:
wb.Worksheets(i).Delete()
wb.Save()
excel.DisplayAlerts = True
excel.Application.Quit()
return
not sure about those modules but u can try win32
from win32com import client
def delete(self, number = 1):
"""
(if the sheet is the first use 1. -1 to use real number)
example: r.delete(1)
"""
sheetnumber = int(number) - 1