I am trying to write some data into an excel file (using openpyxl) after a user filled out a form created in Flask (WTForms). The data gets written to an excel sheet, but every time, I open the excel file, I get a below error. I am not sure what I need to do to stop that warning from appearing.
Excel error
My code:
from openpyxl import Workbook, load_workbook
class MyForm(Form):
Name = StringField('Name: ', [InputRequired("Please enter your name.")])
#app.route('/submit', methods=['POST'])
def submit_form():
Name = form.Name.data
workbook = load_workbook(filename='C:\\users\\TestUser\\Desktop\\Test.xlsx')
worksheet = workbook.active
appendData = worksheet.cell(row=1, column=1, value=(Name))
worksheet.append(appendData)
workbook.save('C:\\users\\TestUser\\Desktop\\Test.xlsx')
worksheet.append([Name]) resolves the issue.
Related
I want to open and edit an excel workbook. However, when I run the following, it always create a new book (Book1) which I don't want.
import xlwings as xw
mypath= #path
app= xw.App()
wb=app.books.open(mypath)
After running, there will always be an unnecessary new Book1 created. Is there anyway to make it tidier?
I tried replacing app=xw.App() with app=xw.App(add_book=False), but it shows error below:
raise XlwingsError("Couldn't find any active App!")
xlwings.XlwingsError: Couldn't find any active App!
I also tried removing the line app=xw.App() and directly open the book with
wb=xw.books.open(mypath)
If I already have an excel file opened, then this worked as I wish, opened the book with any new book created. But if there is no other excel file opened, then the same error as above is raised.
Also tried the following from previous questions. https://stackoverflow.com/questions/11018237/open-excel-application-without-new-workbook
import xlwings as xw
mypath= #path
app= xw.App()
app.ActiveWorkbook.Close(False);
app.visible = True;
wb=app.books.open(mypath)
Error occured
app.ActiveWorkbook.Close(False);
AttributeError: 'App' object has no attribute 'ActiveWorkbook'
This seems to be a very simple question, please bear me since I am very new to Python (and xlwings) and this is my first time asking questions here.
I like to use a context manager since it cleans up nicely at close.
import xlwings as xw
workbook = 'Book1.xlsx'
with xw.App() as app:
wb = xw.Book(workbook)
ws = wb.sheets('Sheet1')
...
wb.save(workbook) # needed only if data is written to the workbook
wb.close()
##----------------------------##
##----------------------------##
import xlwings as xw
workbook = 'yourExcelFile.xlsm'
with xw.App(visible=False, add_book=False) as app:
wb = xw.Book(workbook)
ws = wb.sheets('Sheet1')
# ...
print(ws.range('A1').value)
wb.save(workbook) # <-- Needed only where sheet data changed
wb.app.quit()
Open excel,then click file->New->Blank workbook, we can get a blank workbook. We can input some information.
I want to use Python to save the created Excel to the path we set.
import win32com.client
import os
excel = win32com.client.Dispatch("Excel.Application")
xlsx_fullname = os.path.abspath("Book1")
workBook = excel.Workbooks.Open(xlsx_fullname)
excel.ExecuteExcel4Macro("FDSFORCERECALC(False)")
workBook.Save()
workBook.Close(True)
excel.Application.Quit()
I used this code, but I can't use python to select this excel file. It's not working
Change
xlsx_fullname = os.path.abspath("Book1")
workBook = excel.Workbooks.Open(xlsx_fullname)
...
workBook.Save()
to
workBook = excel.ActiveWorkbook
...
workBook.SaveAs(Filename="c:/path/to/your desired filename.xlsx")
I'd like to upload an excel file in my web app, read the contents of it and display some cells. So basically I don't need to save the file as it's a waste of time.
Relevant code:
if form.validate_on_submit():
f = form.xml_file.data.stream
xml = f.read()
workbook = xlrd.open_workbook(xml)
sheet = workbook.sheet_by_index(0)
I can't wrap my mind around this as I keep getting filetype errors no matter what I try. I'm using Flask Uploads, WTF.file and xlrd for reading the file.
Reading the file works okay if I save it previously with f.save
To answer my own question, I solved it with
if form.validate_on_submit():
# Put the file object(stream) into a var
xls_object = form.xml_file.data.stream
# Open it as a workbook
workbook = xlrd.open_workbook(file_contents=xls_object.read())
I am trying to password protect an entire Excel file (same functionality as File > Protect Workbook > Encrypt with Password) using Python.
I have come across openpyxl and the protection features it offers (https://openpyxl.readthedocs.io/en/stable/protection.html) seems to fulfill this need. I have the following code:
from openpyxl import Workbook
from openpyxl import load_workbook
test_spreadsheet = "test.xlsx"
wb = load_workbook(test_spreadsheet)
wb.security.workbookPassword = "password"
However, I am getting the following error:
AttributeError: 'NoneType' object has no attribute 'workbookPassword'
Does anyone have an idea of what is causing this AttributeError? I have printed the sheetnames from wb and that is correctly printing the tabs in my Excel document.
For a default-constructed workbook, the security property is initialized by default:
self.security = DocumentSecurity()
However, workbooks constructed by reading a workbook are not just default-constructed; they are also manipulated by a Parser object:
wb_part = _find_workbook_part(self.package)
self.parser = WorkbookParser(self.archive, wb_part.PartName[1:], keep_links=self.keep_links)
self.parser.parse()
wb = self.parser.wb
...
self.wb = wb
Parser.init does default-construct a Workbook, but then overrides specific properties with those of the source document:
self.wb.security = package.workbookProtection
This means that for files that had no security settings, the imported workbook object has a value of None for its security property (and thus your error, as None clearly has no attribute workbookPassword).
Your solution is then to create a default WorkbookProtection(), assign it to the workbook, and then set the workbook password.
As the Openpyxl document states "Workbook Protection
To prevent other users from viewing hidden worksheets, adding, moving, deleting, or hiding worksheets, and renaming worksheets, you can protect the structure of your workbook with a password."
It's not the same as File > Protect Workbook > Encrypt with Password.
Also does not work with an existing workbook.
If you run the following code, and open the newly created book 'test.xlsx' you should see it will open without a password however you cannot do any of those actions in italics above unless you go to the 'changes' toolbar and click 'Protect Workbook' then enter the password.
from openpyxl import Workbook
from openpyxl import load_workbook
test_spreadsheet = "test.xlsx"
wb = Workbook()
wb.security.workbookPassword = 'password'
wb.security.lockStructure = True
wb.save(test_spreadsheet)
I don't believe openpyxl or other Python module supports the option you want.
I opened a excel file by using the following code:
from openpyxl import load_workbook
wb = load_workbook('path of the file')
DriverTableSheet = wb.get_sheet_by_name(name = 'name of the sheet')
after that I have to append some values in that excel file..
for that I used the following code
DriverTableSheet.cell(row=1, column=2).value="value"
But it is not responding. Can u guys please guide how to write / append a data in that excel file and save that excel file