如何用xlsx-wri动态写入excel

2024-05-23 20:59:07 发布

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

我想用xlsx writer将数据动态写入excel文件。我从mysql数据库中获取数据,结果如下所示。在

data  = (
    ('Shankar', '100', '100', '200'),
    ('Kumar', '50', '80', '130'),
    ('Shiva', '20', '20', '40'),
    ('Sekar', '20', '20', '40')
)

我想用python中的xlsxwriter将上述数据写入excel文件。预期结果如下

^{pr2}$

请任何人帮助我在python中使用xlsxwriter编写代码


Tags: 文件数据数据库datamysql动态xlsxexcel
3条回答

您可以使用^{}执行此操作:

import pandas as pd

data  = (
    ('Shankar', '100', '100', '200'),
    ('Kumar', '50', '80', '130'),
    ('Shiva', '20', '20', '40'),
    ('Sekar', '20', '20', '40')
)

# Create a dataframe with the data of interest
df = pd.DataFrame(data=list(data), columns=['Name', 'Col1', 'Col2', 'Col3'])

# Export the dataframe to a XLSX file, in Worksheet `sheet1`,
# without the index nor the column names of the dataframe
df.to_excel('data.xlsx', sheet_name='sheet1', index=False, header=False)

这会将以下内容输出到数据.xlsx

enter image description here

试试这个:

import xlsxwriter

data  = (('Shankar','100','100','200'),('Kumar','50','80','130'),('Shiva','20','20','40'),('Sekar','20','20','40'))

# Open the workbook and add a worksheet
workbook = xlsxwriter.Workbook('output.xlsx')
worksheet = workbook.add_worksheet()

# iterate through your tuple of tuples, and write out each cell 
for row, x in enumerate(data):
    for col, y in enumerate(x):
        worksheet.write(row, col, y)

# Make sure to close the workbook 
workbook.close()

得出以下结果输出.xlsx

enter image description here

做这样的事情:

import xlsxwriter
workbook = xlsxwriter.Workbook('my_excel.xlsx')
worksheet = workbook.add_worksheet()

data = (('Shankar','100','100','200'),('Kumar','50','80','130'),('Shiva','20','20','40'),('Sekar','20','20','40'))

### Iterate over the data and write it out row by row.
for row, line in enumerate(data):
    for col, cell in enumerate(line):
        worksheet.write(row, col, cell)

workbook.close()

相关问题 更多 >