How to set print_area and repeat_rows using xlsxwriter, if I need custom sheet names?

Viewed 745

How can I create a xlsx file for which I can specify all the following features using xlsxwriter?

  1. A custom name for each sheet (add_worksheet)
  2. A specific print area (print_area)
  3. Repeatition of the first row of the sheet on every printed page (repeat_rows)

I tried to use (something similar to) the following code:

import xlsxwriter
import pandas as pd
from random import randint

df = pd.DataFrame({'A': [randint(2000, 2001) for x in range(150)],
                   'B': [randint(300, 400) for x in range(150)]})

workbook = xlsxwriter.Workbook('xlsxwriter-problem.xlsx')
main_format = workbook.add_format({'border': 1})
for name, group in df.groupby('A'):
    worksheet = workbook.add_worksheet(str(name))
    worksheet.write(0, 0, 'B')
    for i in range(1, len(group.index)):
        worksheet.write(i, 0, group.iloc[i,1])
    worksheet.set_column(0, 0, None, main_format)
    worksheet.print_area('A1:A95')
    worksheet.repeat_rows(0)
workbook.close()

However, when I open the file in LibreOffice Calc, I notice the last two lines inside the loop seem to be ignored, and I get this unwanted behaviour.

After a while, I found out that these two lines produce the desired behaviour if I use the default sheet names, that is, if I set

worksheet = workbook.add_worksheet()

inside the loop.

Isn't possible to keep the both custom sheet name and the other features?

0 Answers
Related