Xlsxwriter: How to Open an Existing Worksheet in My Workbook

how write with xlsxwriter in excel in a existing file without deleting the old data

XlsxWriter can only create new files. It cannot read or modify existing files.
There is a module called openpyxl that allows you to read and write to preexisting excel files.

Python xlsxwriter - add a worksheet to an existing workbook

I don't think this is still possible with xlsxwriter. Please take a look at this answer for help

Can't append Excel sheet with xlsxwriter

Actually i found that xlsxwriter can't append it cas only write (erase other sheets if exists).
The solution is to use openpyxl and this is an exemple of code :

import openpyxl 
from openpyxl import Workbook # Module needed for creating new workbook
from openpyxl import load_workbook # Module needed for loading existing workbook

wb = load_workbook(filename)
ws = wb["sheetName"]

for row in dataframe_to_rows(dataframe, index=False, header=True):
ws.append(row)
wb.save(filename)

How to add a new work sheet to work book in xlsxwriter

Here is a sample code.
the workbook constructor needs to be created outside of the for loop and it does what you are looking for!

Input csv files:

enter image description here

SAMPLE CODE

import os
import glob
import xlsxwriter
import csv

flist = [os.path.basename(x) for x in glob.glob(os.getcwd() + '\\*.csv')]

workbook = xlsxwriter.Workbook('split_book.xlsx')

for sh in flist:
worksheet = workbook.add_worksheet(sh)
with open(sh, 'rb') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)

workbook.close()

OUTPUT

enter image description here



Related Topics



Leave a reply



Submit