Python – Write CSV files using xlsxwriter ByteIO objects

Write CSV files using xlsxwriter ByteIO objects… here is a solution to the problem.

Write CSV files using xlsxwriter ByteIO objects

I’m creating a .xlsx file using the xlsxwriter ByteIO object, and I want to create a . CSV file. Is it possible?

Here is my code :

outputStr=BytesIO()
workbook = xlsxwriter. Workbook(outputStr,{'in_memory': True})
worksheet = workbook.add_worksheet()

# Some data we want to write to the worksheet.
row = 0
col = 0
expenses=(['OriginalURL','NormalizedURL','Response','DuplicateOf','SourceId', 'RelatedSources'],)

for OriginalURL,NormalizedURL,Response,DuplicateOf,SourceId,RelatedSources in (expenses):
    worksheet.write(row, col,   OriginalURL)
    worksheet.write(row, col+1, NormalizedURL)
    worksheet.write(row, col+2, Response)
    worksheet.write(row, col+3, DuplicateOf)
    worksheet.write(row, col+4, SourceId)
    worksheet.write(row, col+5, RelatedSources)
    row += 1

workbook.close()

Without storing the file, I use the “outputStr” object to attach the “.xlsx” file to the JIRA cloud.

Here is the Jira code (using .xlsx files):

thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='Result.xlsx')

I

want to attach a CSV file with the same result (I tried the same code with .csv but it doesn’t work):

thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='CopyResult.csv')

I’m getting this error in a CSV file:

The file format and extension of “.xls” do not match. The file may be corrupted or unsafe. Do not open it unless you trust its source. Do you still want to open it? ”

Help me! Thank you.

Solution

You can use the built-in >csv module to write CSV with XLSX files, you just need to create it slightly differently:

import csv
import io
import xslxwriter

xlsx_data = io. BytesIO()
csv_data = io. StringIO()  # on Python 2.x use `io. BytesIO()`

# XLSX part
workbook = xlsxwriter. Workbook(xlsx_data, {'in_memory': True})
worksheet = workbook.add_worksheet()

# CSV part
csv_writer = csv.writer(csv_data)

# Some data we want to write to the worksheet.
expenses=(['OriginalURL', 'NormalizedURL', 'Response', 'DuplicateOf',
           'SourceId', 'RelatedSources'],)

for row, data in enumerate(expenses):
    # XSLX part
    worksheet.write_row(row, 0, data)  # if needed, add an offset to the row/column

# CSV part
    csv_writer.writerow(data)

workbook.close()

# CSV data available in csv_data, XLSX data available in xlsx_data

It’s not clear from your question whether you want to create them both – if not, just remove the XLSX section (you can do csv_writer.writerows(expenses) directly, without having to iterate through individual lines).

Related Problems and Solutions