初識python: xlsxwriter 將數據寫入Excel


使用 xlsxwriter 模塊將數據寫入excel 。

 

#!/user/bin env python
# author:Simple-Sir
# time:2020/9/24 12:51
# 使用 xlsxwriter 將數據寫入Excel
import xlsxwriter

xlsname = 'test.xlsx'  # 定義xlsx文件名稱
xls = xlsxwriter.Workbook(xlsname)  # 創建xlsx文件,若已存在則覆蓋。

# 定義sheet名稱及各sheet表頭字段
stname_fields_dict = {'第一個sheet': ['日期', '姓名', '年齡'],
                      '第二個sheet': ['日期', 'ID','科目','成績' ],
                      '測試': ['日期', 'ID','測試名稱','測試結果' ]
                      }

st_list=[]  # 定義一個列表用於存儲所有要寫入excel的數據

# sheet1的數據
st_list.append([['20200924','小明',22],
           ['20200924','小李',24],
           ['20200924','小王',23]
           ])
# sheet2的數據
st_list.append([['20200924','92401','python',89],
                ['20200924','92402','語文',90],
                ['20200924','92403','數學',98],
                ['20200924','92404','英語',96]
                ])
# sheet3的數據
st_list.append([['20200924','ts01','python',89],
                ['20200924','ts02','語文',90],
                ['20200924','ts03','數學',98],
                ['20200924','ts04','英語',96],
                ['20200924','ts02','語文',90],
                ['20200924','ts03','數學',98],
                ['20200924','ts04','英語',96]
                ])

# 循環寫入數據
for indx_dict,stname_fields in enumerate(stname_fields_dict.values()):  # stname_fields_dict.values() sheet表頭字段
    sh_name = list(stname_fields_dict.keys())[indx_dict]
    sheet = xls.add_worksheet(sh_name)  # 添加sheet、stname_fields_dict.keys() sheet名稱
    for indx, field in enumerate(stname_fields):
        sheet.write(0, indx, field)  # 寫入表頭

    line_list = st_list[indx_dict]  # 獲取sheet數據
    line_count = line_list.__len__()  # 獲取數據條數

    x = 1  # 從第二行開始寫內容
    while x < line_count + 1:
        line = line_list[x - 1]  # 按行順序遍歷
        # 寫入各個字段值
        for i, item in enumerate(line):
            if type(item) == type(None):  # 空值處理
                sheet.write(x, i, '')
            else:
                sheet.write(x, i, item)  # x 行,i 列, item 值
        x += 1
    print('%s共寫入%d條數據。' % (sh_name, line_count))
xls.close()

print('執行完成!')
使用 xlsxwriter 將數據寫入Excel

 

執行結果:

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM