我无法使用openpyxl模块写入excel文件。到目前为止,我能够编写此代码
from openpyxl.workbook import Workbook
import datetime
header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [
[u'name1', u'email1@yahoo.com', 9929283421.0, u'xxxx'],
[u'name2', u'email2@xyz.com', 9994191988.0, u'xxxx']
]
wb = Workbook()
cur_date = str(datetime.date.today())
log_file = "%s/%s_%s_errorlog.xlsx" % (settings.MEDIA_ROOT,
os.path.splitext(file_name)[0],
cur_date)
log_csv = wb.worksheets[0]
for i in range(1, len(header) + 1):
log_csv.cell(row = 1 ,column = i).value = header[i - 1]
wb.save(log_file)
error_count = 0
for each_row in new_data:
error_count += 1
for i in range(1, len(each_row) + 1):
log_csv.cell(row = error_count ,column = i).value = each_row[i - 1]
wb.save(log)
文件已创建,但已损坏,我无法使用操作系统(ubuntu)提供的Excel文件阅读器(LibreOffice)打开它。此外,该文件的内容不可读。不确定我做错了什么
答案 0 :(得分:7)
from openpyxl.workbook import Workbook
header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [[u'name1', u'email1@yahoo.com', 9929283421.0, u'xxxx'],
[u'name2', u'email2@xyz.com', 9994191988.0, u'xxxx']]
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active
ws1.title = "range names"
ws1.append(header)
for row in new_data:
ws1.append(row)
wb.save(filename = dest_filename)
我可以像上面那样将内容写入xlsx。