encrypting excel workbook sheet with python - python

I'm currently implementing a tool to automise parts of my daily work. Therefore I need to create a python tool which creates an excel-file (workbook) with several informations and encrypts the sheets of the file.
The first part which creates the file and fills it with the data works perfectly.
But the encryption doesn't work at all.
I'm using win32com, win32com.client and openpyxl. The workbook hast two different sheets, named "1" and "2".
My Workbook:
import win32com.client
import os, sys, win32com, os.path, time
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True
workbook = excel.Workbooks.Open(reading_path) ####this is the path where the file is stored
sheet = workbook.Worksheets(1)
So I searched through other topics and got the following:
import openpyxl
sheet.protection.set_password('test')
sheet.save(saving_path)
Unfortunately this doesn't work... My shell response an AttributeError. In Detail:
AttributeError: <unknown>.set_password
Does someone knows another way how to encrypt just the pages in excel with python?
Thanks a lot for your help!

It is not entirely clear what you mean by "encrypting the sheet" as the openpyxl code you refer to has nothing to do with encryption; see the warning in the documentation. Excel does support encryption of entire workbooks though, but that appears to be different from what you want.
In any case, your code fails because the sheet you get from win32com is a wildly different beast than what openpyxl expects. For example, sheet being based on COM requires an Excel process to run for manipulation to be possible, while openpyxl does not even require Excel to be available on the host machine.
Now in your particular case, you do not actually need openpyxl (although you might find that using it over win32com has plenty of benefits), and you could stay entirely within COM. As such, adding password protection is possible through Worksheet.Protect which in your case would boil down to simply running
sheet.Protect('test')

Related

Load only a single sheet from a large workbook with Python

Using Python 3.7. I have several .xlsx workbooks with 34 sheets each, most of which have conditional formatting and charts, but all I'm actually after is a cell with specified text that's somewhere on the first sheet of each book. The workbook is not protected but the sheet is, and I don't know the password, so I can't use pandas.read_excel; using openpyxl/load_workbook, it takes ages to load and I get lots of errors about it not being able to handle conditional formatting etc. I then have to search the sheet for the text.
Is there an easy, quick way of loading just the first sheet (or a named sheet)? The pandas code is very quick and easy, but I can't use it :(
Not completely sure about that but I can recommend trying "read-only" mode from openpyxl
https://openpyxl.readthedocs.io/en/stable/optimized.html
It does not fetch the full file but read it in so-called "lazy" mode. Thus you can jump to the cell you need.
It also allows to start reading from the specific sheet
Note that closing file is mandatory

Update an Excel sheet in real time using Python

Is there a way to update a spreadsheet in real time while it is open in Excel? I have a workbook called Example.xlsx which is open in Excel and I have the following python code which tries to update cell B1 with the string 'ID':
import openpyxl
wb = openpyxl.load_workbook('Example.xlsx')
sheet = wb['Sheet']
sheet['B1'] = 'ID'
wb.save('Example.xlsx')
On running the script I get this error:
PermissionError: [Errno 13] Permission denied: 'Example.xlsx'
I know its because the file is currently open in Excel, but was wondering if there is another way or module I can use to update a sheet while its open.
I have actually figured this out and its quite simple using xlwings. The following code opens an existing Excel file called Example.xlsx and updates it in real time, in this case puts in the value 45 in cell B2 instantly soon as you run the script.
import xlwings as xw
wb = xw.Book('Example.xlsx')
sht1 = wb.sheets['Sheet']
sht1.range('B2').value = 45
You've already worked out why you can't use openpyxl to write to the .xlsx file: it's locked while Excel has it open. You can't write to it directly, but you can use win32com to communicate with the copy of Excel that is running via its COM interface.
You can download win32com from https://github.com/mhammond/pywin32 .
Use it like this:
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
wb=xlApp.Workbooks.Item("MyExcelFile.xlsx")
ws=wb.Sheets("MyWorksheetName")
At this point, ws is a reference to a worksheet object that you can change. The objects you get back aren't Python objects but a thin Python wrapper around VBA objects that obey their own conventions, not Python's.
There is some useful if rather old Python-oriented documentation here: http://timgolden.me.uk/pywin32-docs/contents.html
There is full documentation for the object model here: https://msdn.microsoft.com/en-us/library/wss56bz7.aspx but bear in mind that it is addressed to VBA programmers.
If you want to stream real time data into Excel from Python, you can use an RTD function. If you've ever used the Bloomberg add-in use for accessing real time market data in Excel then you'll be familiar with RTD functions.
The easiest way to write an RTD function for Excel in Python is to use PyXLL. You can read how to do it in the docs here: https://www.pyxll.com/docs/userguide/rtd.html
There's also a blog post showing how to stream live tweets into Excel using Python here: https://www.pyxll.com/blog/a-real-time-twitter-feed-in-excel/
If you wanted to write an RTD server to run outside of Excel you have to register it as a COM server. The pywin32 package includes an example that shows how to do that, however it only works for Excel prior to 2007. For 2007 and later versions you will need this code https://github.com/pyxll/exceltypes to make that example work (see the modified example from pywin32 in exceltypes/demos in that repo).
You can't change an Excel file that's being used by another application because the file format does not support concurrent access.

Python script for pasting values into .xls

I am creating a Python script to paste values pulled from another file into an Excel template.
The Excel template contains many macros that process the data it is given. This data is then sent to the clipboard, and the unsaved Excel file is then closed.
I have used a combo of xlwt and xlrd (it's a .xls file) to try and write to the Excel file, but it seems that these commands access the file without explicitly opening it (the Excel file never comes on screen).
I was curious if anyone could point me in the right direction of some tools that would allow me to explicitly open an Excel file (e.g. subprocess.call()), paste the data into some cells, then let the user do the rest.
Any help or criticism is appreciated.
EDIT:
I have been trying to use pywin32 for my purposes. It's not quite working. While it can successfully open the Excel file and run the macro, it cannot pass any values into the textbox of the macro.
Here is my current code:
import win32com.client as win32
import time
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'C:\Users\me\Desktop\file.xlsm')
excel.Visible = True
#if I run wb.Application.SendKeys(1) here, it places a 1 into a cell on the worksheet
wb.Application.Run('Set_Up_Sheet') #running the macro, which successfully launches
time.sleep(2)
wb.Application.SendKeys(1) #this seems to have no effect
How can I send values to this macro's textbox?

Add sheet to created workbook from another workbook

I create new workbooks via xlsxwriter. In every of them I need to have formated header sheet, which is stored in another template workbook. I know it is impossible to do with xlsxwriter, coz I cannot open template workbook with this.
I thought to do that by xlrd, copy this sheet and then with xlsxwriter write it to created workbook.
But is it possible? To use combination of those two libraries?
I know this question is without even any code, but I'm lame with python and if you could give me any advice or something to deal with my problem I will be gratefull.
xlrd and xlswriter aren't really designed to work together. Consider switching to the pyopenxl library, which allows both reading and writing of spreadsheets and might allow you to do what you need quite easily.

Can I password protect excel work book with XLRD?

I want to deliver an EXCEL application and I'm finding out whether I can password protect a whole work book with Python and XLRD libray? Does any one around know how I can do this with the XLRD on python?
As the README says, in the "Outside the current scope" section:
Unlikely to be done:
Handling password-protected (encrypted) files.
On top of that, note that xlrd is only for reading data from Excel files, not generating or modifying them (xlwt does that). So, even if it were possible, xlrd wouldn't be the way to do it.

Categories

Resources