我正在使用xlsxwriter ByteIO对象创建一个.xlsx文件,使用与我想创建.CSV文件相同的对象。有可能吗?
这是我的代码:
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()
在不存储文件的情况下,我使用“ outputStr”对象将“ .xlsx”文件附加到JIRA云中。
以下是吉拉代码(使用.xlsx文件):
thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='Result.xlsx')
我要附加具有相同结果的CSV文件(我尝试使用.csv的相同代码,但无法正常工作):
thisJira.add_attachment(issue=new_issue, attachment=outputStr, filename='CopyResult.csv')
我在CSV文件中收到此错误:
“。xls”的文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非您信任它的来源,否则请不要打开它。是否要打开它?” >
救救我!谢谢。
答案 0 :(得分:2)
您可以使用内置的csv
模块在XLSX文件旁边编写CSV,而只需要稍微不同地创建它即可即可:
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(row)
workbook.close()
# CSV data available in csv_data, XLSX data available in xlsx_data
不清楚您是否要同时创建它们-如果不是,则只需删除XLSX部分(您可以直接执行csv_writer.writerows(expenses)
,而无需遍历单个行)