欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python自動(dòng)化辦公之Excel數(shù)據(jù)的寫(xiě)入

 更新時(shí)間:2022年05月19日 08:40:15   作者:渴望力量的哈士奇  
這篇文章主要為大家詳細(xì)介紹一下Python中excel的寫(xiě)入模塊- xlsxwriter,并利用該模塊實(shí)現(xiàn)Excel數(shù)據(jù)的寫(xiě)入,感興趣的小伙伴可以了解一下

上一章節(jié)我們學(xué)習(xí)了 excel 的讀取模塊 - xlrd ,今天章節(jié)將學(xué)習(xí) excel 的寫(xiě)入模塊 - xlsxwriter 。通過(guò)該章節(jié)的學(xué)習(xí),就可以自己主動(dòng)生成 excel 文件了。

Excel 寫(xiě)入 - xlsxwriter

xlsxwriter 的安裝

安裝方式:

pip install xlsxwriter

若安裝不上或者安裝速度過(guò)慢,可以換國(guó)內(nèi)的鏡像源地址:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple xlsxwriter

導(dǎo)入:

import xlsxwriter

xlsxwriter 常用函數(shù)介紹

初始化 excel 對(duì)象

book = xlsxwriter.Workbook()    # 生成 excel 對(duì)象
sheet = book.add.sheet(工作簿名稱)    # 生成 excel 對(duì)象的工作簿名稱

獲取工作簿

函數(shù)名說(shuō)明參數(shù)
xlsxwriter.Workbook()生成 excel 對(duì)象excel 文件名
add_worksheet()添加工作簿工作簿名稱
sheet.write()書(shū)寫(xiě)內(nèi)容行索引、列索引、內(nèi)容
book.close()關(guān)閉 excel 對(duì)象無(wú)

代碼示例如下:

# coding:utf-8

import xlsxwriter  # pip install xlsxwriter

excel = xlsxwriter.Workbook('write.xlsx')       # 初始化 excel 對(duì)象
book = excel.add_worksheet('study')             # 添加工作簿

title = ['姓名', '性別', '年齡', '成績(jī)', '等級(jí)']   # 定義 write.xlsx 的首行內(nèi)容

for index, data in enumerate(title):        # for循環(huán) 利用枚舉函數(shù)將 title 的內(nèi)容寫(xiě)入 "write.xlsx" 的首行
    book.write(0, index, data)
excel.close()

運(yùn)行結(jié)果如下:

小實(shí)戰(zhàn)

將項(xiàng)目中的 study.xlsx 文件的內(nèi)容寫(xiě)入 write.xlsx

代碼示例如下:

# coding:utf-8

import xlsxwriter  # pip install xlsxwriter
import xlrd

# excel = xlsxwriter.Workbook('write.xlsx')       # 初始化 excel 對(duì)象
# book = excel.add_worksheet('study')             # 添加工作簿
#
# title = ['姓名', '性別', '年齡', '成績(jī)', '等級(jí)']   # 定義 write.xlsx 的首行內(nèi)容
#
# for index, data in enumerate(title):        # for循環(huán) 利用枚舉函數(shù)將 title 的內(nèi)容寫(xiě)入 "write.xlsx" 的首行
#     book.write(0, index, data)
# excel.close()

def read():             # 定義一個(gè) read 函數(shù)讀取 "study.xlsx" 文件
    result = []
    excel = xlrd.open_workbook('study.xlsx')
    book = excel.sheet_by_name('學(xué)生手冊(cè)')
    for i in book.get_rows():
        content = []
        for j in i:
            content.append(j.value)
        result.append(content)
    return result


def write(content):     # 定義一個(gè) write 函數(shù) 將讀取到 "study.xlsx" 的內(nèi)容寫(xiě)入到 "write.xlsx" 文件
    excel = xlsxwriter.Workbook('write.xlsx')
    book = excel.add_worksheet('study')

    for index, data in enumerate(content):
        print(data)		# 調(diào)試打印寫(xiě)入的每一行內(nèi)容
        for sub_index, sub_data in enumerate(data):
            # print(sub_index, sub_data)
            book.write(index, sub_index, sub_data)
    excel.close()

if __name__ == '__main__':
    result = read()
    write(result)

運(yùn)行結(jié)果如下:

到此這篇關(guān)于Python自動(dòng)化辦公之Excel數(shù)據(jù)的寫(xiě)入的文章就介紹到這了,更多相關(guān)Python Excel數(shù)據(jù)寫(xiě)入內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論