matsbauer
matsbauer

Reputation: 434

Xlsxwriter Python3 Error

I am having troubles with my python3 script, in regards to closing xlsxwriter. I have included workbook.close(), but this seems to result in some kind of error. Does anyone know what the problem is?

import xlsxwriter
import statistics

workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

power = []

for row in list:
    power.append(row)
    worksheet.write(i, col, row)
    col += 1

worksheet.write(i, col, statistics.median(power))

workbook.close()

Traceback (most recent call last):
  File "example.py", line 71, in <module>
    workbook.close()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/workbook.py", line 311, in close
    self._store_workbook()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/workbook.py", line 619, in _store_workbook
    xml_files = packager._create_package()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/packager.py", line 139, in _create_package
    self._write_shared_strings_file()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/packager.py", line 286, in _write_shared_strings_file
    sst._assemble_xml_file()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 54, in _assemble_xml_file
    self._write_sst_strings()
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 84, in _write_sst_strings
    self._write_si(string)
  File "/usr/local/lib/python3.4/dist-packages/xlsxwriter/sharedstrings.py", line 96, in _write_si
    string = re.sub('(_x[0-9a-fA-F]{4}_)', r'_x005F\1', string)
  File "/usr/lib/python3.4/re.py", line 179, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: can't use a string pattern on a bytes-like object

Upvotes: 3

Views: 1872

Answers (2)

jmcnamara
jmcnamara

Reputation: 41524

I added some variable initialization to the example to get it to compile and it appears to run correctly on Python 2 and 3:

import xlsxwriter
import statistics

workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})

power = []

# I added these variables to the OP program.
list = [1, 2, 3, 4, 5]
i = 0
col = 0

for row in list:
    power.append(row)
    worksheet.write(i, col, row)
    col += 1

worksheet.write(i, col, statistics.median(power))

workbook.close()

Output:

enter image description here

I guess the difference between this and the your example is the contents of the list array.

Could you update your question with an example that demonstrates the actual issue?

Upvotes: 1

You need to convert a byte-like object into a string using .decode, e.g. obj = response.read().decode('utf-8').

In your case the objects inside list must be of type bytes, convert them into string.

See Convert bytes to a Python String

Upvotes: 0

Related Questions