SoFunction
Updated on 2024-10-30

Examples of 5 ways to generate data into an Excel file in python

1、xlwt

import xlwt
wb = ()
# Add a table
ws = wb.add_sheet('test')
# 3 parameters are row number, column number, and content
# It's important to note that the row and column numbers start at zero.
# (0, 0, 'column 1') # One by one
# (0, 1, 'column 2')
# (0, 2, 'column 3')
for i in range(3):
    for j in range(2):
        (i, j, f'(prefix indicating ordinal number, e.g. first, number two etc){i+1}classifier for objects in rows such as words,(prefix indicating ordinal number, e.g. first, number two etc){j+1}columns')
# Save excel file
('./')

Effect:

2、openpyxl

from openpyxl import Workbook
outwb = Workbook()
outws = [0]
mongoDB_data = [{'name':'Chow','age':18,'sex':'Male'},
                {'name':'King','age':19,'sex':'Male'},
                {'name':'Lee','age':16,'sex':'Female'}]
(['Name','Age','Gender'])  # Start by adding a header row
# Traverse the outer list
for new_dict in mongoDB_data:
    a_list = []
    # Iterate through each of the inner dictionary dicts and store each value of the dict into the list
    for item in new_dict.values():
        a_list.append(item)
    # sheet just append list
    (a_list)
(r'')
print('Data saved to excel successfully')

Effect:

3、xlsxwriter

import xlsxwriter as xw
workbook = ('') # Create workbooks
worksheet1 = workbook.add_worksheet("sheet1") # Create sub-tables
() # Activation table
title = ['Name','Age','Gender'] # Set up table headers
data = [['Chow',18,'Male'],['King',19,'Male'],['Lee',16,'Female']]
worksheet1.write_row('A1',title) # Write table headers starting in cell A1
i = 2 # Write data from the second line
for j in range(len(data)):
    insertData = [data[j][0],data[j][1],data[j][2]]
    row = 'A' + str(i)
    worksheet1.write_row(row, insertData)
    i += 1
() # close table

Effect:

4、pandas

import pandas as pd
data = [['Chow','King','Lee'],[18,19,16],['Male','Male','Female']]
dfData = { # Setting up DataFrame required data with a dictionary
        'Name':data[0],
        'Age':data[1],
        'Gender':data[2]
    }
df = (dfData) # Create DataFrame
df.to_excel('',index=False) # save a watch,Remove raw index columns(0,1,2...)

Effect:

5、openpyxl

import openpyxl as op
data = [['Chow','King','Lee'],[18,19,16],['Male','Male','Female']]
wb = () # Create workbook objects
ws = wb['Sheet'] # Create sub-tables
(['Name','Age','Gender']) # Add table headers
for i in range(len(data[0])):
    d = data[0][i], data[1][i], data[2][i]
    (d) # Write one line at a time
('')

Effect:

summarize

to this article on the python data will be generated into an Excel file of the five methods of the article is introduced to this, more relevant python data to generate Excel file content, please search for my previous posts or continue to browse the following related articles I hope you will support me more in the future!