如何使用XLSX Writer动态写入Excel

时间:2018-12-12 07:14:05

标签: python excel pandas dataframe xlsxwriter

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

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

我想使用python中的xlsxwriter将以上数据写入excel文件。预期结果应如下所示

  Shankar 100  100  200
  Kumar    50   80  130
  Shiva    20   20   40 
  Sekar    20   20   40

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

3 个答案:

答案 0 :(得分:2)

您可以使用pandas进行此操作:

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)

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

enter image description here

答案 1 :(得分:2)

尝试一下:

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()

其中给出以下 output.xlsx

enter image description here

答案 2 :(得分:2)

执行以下操作:

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()