Jane
Jane

Reputation: 95

Create an excel file in a different directory

if not os.path.isdir("DirectoryName"):
    os.makedirs("DirectoryName")

if not os.path.isfile('FileName.xlsx'):
    wb = openpyxl.Workbook()  
    dest_filename = 'FileName.xlsx' 

I have the following problem: I want to create a directory in the same directory where I have python files and to create the FileName.xlsx in the directory: DirectoryName and I haven't found out how to do that yet.¿Could you help me?

Thanks

Upvotes: 4

Views: 15258

Answers (4)

Mu Dong Liu
Mu Dong Liu

Reputation: 21

You can use the xlsxwriter module :

import xlsxwriter
path = "...";
filename = "file.xlsx";
wb = xlsxwriter.Workbook(path + filename);

Upvotes: 2

user1846747
user1846747

Reputation:

Try this

if not os.path.exists("DirectoryName"):
    os.makedirs("DirectoryName")
filepath = 'DirectoryName/FileName.xlsx'
if not os.path.isfile(filepath):
    wb = openpyxl.Workbook(filepath)  
    wb.save(filename = filepath)

Upvotes: 0

George Sovetov
George Sovetov

Reputation: 5238

Documentation says you can wb.save(os.path.join('DirectoryName', 'FileName.xlsx'), as_template=False). With dest_filename = 'FileName.xlsx' you just assign value to variable. So try:

if not os.path.isdir("DirectoryName"):
    os.makedirs("DirectoryName")

if not os.path.isfile('FileName.xlsx'):
    wb = openpyxl.Workbook()  
    dest_filename = 'FileName.xlsx' 
    wb.save(os.path.join('DirectoryName', dest_filename), as_template=False)

Note that directory where you file is may not be same as you current directory related to which your path is.

Upvotes: 6

ferdy
ferdy

Reputation: 7716

Just use wb.save(file_path) to create your workbook.

import openpyxl, os

if not os.path.isdir("DirectoryName"):
    os.makedirs("DirectoryName")

file_path = 'DirectoryName/Filename.xlsx'

if not os.path.isfile(file_path):
    wb = openpyxl.Workbook()  # open a workbook
    ws = wb.active  # get the active worksheet

    # do your manipulation

    wb.save(file_path)

Upvotes: 0

Related Questions