使用xlwt与openpyx

2024-05-14 14:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些关于PYTHON中openpyxl的帮助。我已经非常成功地使用了xlwt,但是现在我有一些文件(在MySQL工作台中)包含65000多行。我知道我可以创建一个CSV文件,但XLSX是首选输出。我可以使用openpyxl创建一个工作簿,但是我没有成功地将MySQL数据放入表中。使用xlwt的程序的主要部分非常简单(见下文)。我只是不知道如何使用openpyxl做同样的事情。我尝试了很多不同的组合和解决方案。我只是在“结果中的x”之后卡住了。

file_dest = "c:\home\test.xls"
result = dest.execute("select a, b, c, d from filea")
for x in result:
    rw = rw + 1
    sheet1 = book.add.sheet("Sheet 1")
    row1 = sheet1.row(rw)
    row1.write(1, x[0])
    row1.write(1, x[1])
    row1.write(1, x[2])
    row1.write(1, x[3])
book.save(file_dest)

Tags: 文件csvmysqlresultxlsxfilewritedest
2条回答

举个小例子:

wb = Workbook(encoding='utf-8')
ws = wb.worksheets[0]
row = 2
ws.title = "Report"
ws.cell('A1').value = "Value"
ws.cell('B1').value = "Note"
for item in results:
    ws.cell('A%d' % (row)).value = item[0]
    ws.cell('B%d' % (row)).value = item[1]
    row += 1

http://pythonhosted.org//openpyxl/

这是使用append()的一个很好的用例:

Appends a group of values at the bottom of the current sheet.

If it’s a list: all values are added in order, starting from the first column

import openpyxl

file_dest = "test.xlsx"

workbook = openpyxl.Workbook()
worksheet = workbook.get_active_sheet()

result = dest.execute("select a, b, c, d from filea")
for x in result:
    worksheet.append(list(x))

workbook.save(file_dest)

相关问题 更多 >

    热门问题