【问题标题】:encrypting excel workbook sheet with python用python加密excel工作簿表
【发布时间】:2018-07-27 17:53:22
【问题描述】:

我目前正在实施一种工具来自动化我的部分日常工作。因此,我需要创建一个 python 工具来创建一个包含多个信息的 excel 文件(工作簿)并加密文件的工作表。 创建文件并用数据填充文件的第一部分工作得很好。

但是加密根本不起作用。 我正在使用 win32com、win32com.client 和 openpyxl。工作簿有两个不同的工作表,分别命名为“1”和“2”。

我的工作簿:

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)

于是我搜索了其他主题,得到了以下信息:

import openpyxl    
sheet.protection.set_password('test') 
sheet.save(saving_path) 

不幸的是,这不起作用...我的 shell 响应一个 AttributeError。详细:

AttributeError: <unknown>.set_password

有人知道如何用 python 只加密 excel 中的页面吗?

非常感谢您的帮助!

【问题讨论】:

    标签: python excel encryption openpyxl win32com


    【解决方案1】:

    您所说的“加密工作表”是什么意思并不完全清楚,因为您所指的openpyxl 代码与加密无关;请参阅the documentation 中的警告。 Excel 确实支持对整个工作簿进行加密,但这似乎与您想要的不同。

    无论如何,您的代码都会失败,因为您从win32com 获得的sheetopenpyxl 所期望的完全不同。例如,sheet 基于 COM 需要运行 Excel 进程才能进行操作,而 openpyxl 甚至不需要 Excel 在主机上可用。

    现在在您的特定情况下,您实际上并不需要openpyxl(尽管您可能会发现在win32com 上使用它有很多好处),您可以完全留在COM 中。因此,可以通过 Worksheet.Protect 添加密码保护,在您的情况下可以归结为简单地运行

    sheet.Protect('test')
    

    【讨论】:

      猜你喜欢
      • 2017-12-21
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2017-08-02
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多