Openpyxl is not saving the excel file, why? - python

here is my code:
import openpyxl as op
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl import worksheet
path = ...
op.load_workbook(path)
wb = Workbook()
ws2 = wb.create_sheet('Sheet2')
wb.save(filename = 'NameOfTheFile.xlsx')
Now everything works, except saving the file, when I add:
print(wb.sheetnames)
it does print out the Sheet2 I just added, but for some reason when I go to the documents where the file is, it does not update it, that sheet is nowhere to be found.

Related

Moving data from multiple csv files to xlsx files

I have a folder that contains 2 more folders. Inside each folder is a csv and xlsx file.
Ex:
test (folder 1)
test.csv
test.xlsx
test2 (folder 2)
test2.csv
test2.xlsx
I have a working script that moves data from a csv file to a xlsx file.
Say ‘test.csv’ contains the following data:
A
B
test.com
yes
test.com/dl
no
1.1.1.1
yes
The code below will move that data into test.xlsx:
from openpyxl import load_workbook
import csv
wb = load_workbook(“D:\\local\\test\\test\\test.xlsx”)
ws = wb.active
with open(“D:\\local\\test\\test\\test.csv”, ‘r’) as f:
for row in csv.reader(f):
ws.append(row)
wb.save(“D:\\local\\test\\test\\test.xlsx”)
Is there an easy way to move all data from ‘test.csv’ to ‘test.xlsx’ and ‘test2.csv’ to ‘test2.xlsx’ at once? The names of the csv and xlsx files will not always be the same but the location will.
I have tried the following but it returns a traceback error:
from openpyxl import load_workbook
import csv
wb = load_workbook(“D:\\local\\test\\{}\\{}.xlsx”)
ws = wb.active
with open(“D:\\local\\test\\{}\\{}.csv”, ‘r’) as f:
for row in csv.reader(f):
ws.append(row)
wb.save(“D:\\local\\test\\{}\\{}.xlsx”)
Thanks!
Assuming that the .xlsx files already exist and are empty, you can use the code below to copy the content of multiple .csv files to those .xlsx files (that have the same stem/filename).
import os
from pathlib import Path
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
directory = r'D:\local\test'
for file in Path(directory).glob('*/*.csv'):
df = pd.read_csv(file, encoding='utf-8-sig')
excel_path = os.path.splitext(file)[0]+'.xlsx'
wb = load_workbook(excel_path)
ws = wb.active
for r in dataframe_to_rows(df, index=False, header=True):
ws.append(r)
wb.save(excel_path)

python - pandas with openpyxl damages my workbook

Using pandas with the openpyxl engine I want to open an excel woorkbook and add a sheet.
Because, the sheets are growing and getting quit big I want to create a new sheet without reading all the other sheet.
So instead of xlsxwriter, I did start using openpyxl, however I get the following issue that the file gets damaged and needs to recovered by excel.
After that, when I run it a second time, I get the python error that the excel file is 'raise BadZipFile("File is not a zip file")'.
This my test code:
import openpyxl
import pandas
from pandas import ExcelWriter
from pandas import ExcelFile
from openpyxl import Workbook
from openpyxl import load_workbook
sheet1 = 'sheet1'
sheet2 = 'sheet2'
if os.path.exists(filename):
workbook = openpyxl.load_workbook(filename)
else:
workbook = Workbook()
writer = pandas.ExcelWriter(filename, engine='openpyxl')
writer.book = workbook
df_1.to_excel(writer, sheet_name=sheet1)
writer.save()
writer.close()
time.sleep(2) # to give it some time. But doesn't help :(
if os.path.exists(filename):
workbook = openpyxl.load_workbook(filename)
else:
workbook = Workbook()
writer = pandas.ExcelWriter(filename, engine='openpyxl')
writer.book = workbook
df_2.to_excel(writer, sheet_name=sheet2)
writer.save()
writer.close()
Any suggestions how to solve this? Or do I miss something?
btw, excel 365 - 16.46 macOS

Open and modify specific worksheet in excel workbook

I am trying to open and format a specific Excel worksheet. However I am having trouble trying to find out how to look at a specific worksheet.
The code I'm trying to use to open the workbook and go to a specific worksheet and then change the font for specific cells is:
from openpyxl import Workbook
def applyValidations(path,tabname):
workbook = Workbook(path)
worksheet = workbook[tabname]
c = worksheet['A1:A5']
c.font = Font(size=22)
The error I'm getting is:
KeyError: 'Worksheet Department Data does not exist.'
Department Data is the name of the worksheet which does exist in the workbook.
Here's some code I use regularly with openpyxl, which may solve your Q:
from openpyxl import load_workbook
wb = load_workbook(filename=data_file, read_only=True)
ws = wb.active
print(wb.sheetnames)

Why is the below Python program showing error?

On executing the below code it shows error
load_workbook() got an unexpected keyword argument 'read_only'
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook(filename="textxl.xlsx", read_only = True)
wb2 = Workbook()
print wb.get_sheet_names()
wb2 = wb
wb2.save('balances.xlsx')
I want to know the reason

Is there a way to edit/save an opening (in excel) xlsx file?

I want to do something like this:
import openpyxl as x
wb = x.load_workbook(filename)
# do some edit to the workbook
wb.save(filename)
The file specified by the filename is opening in Excel. Excel is locking the file so I will get permission denied error running the above code. Is there a way to edit/save it?
from openpyxl import load_workbook
ifile = 'Whales.xlsx'
wb = load_workbook(filename=ifile)
# do some edit to the workbook
wb.save(ifile)

Categories