當前位置:首頁 » 編程語言 » python處理excel文件

python處理excel文件

發布時間: 2025-02-06 16:36:09

『壹』 如何用python讀取excel

使用Python處理Excel文件時,主要依賴於xlrd和xlwt這兩個庫。首先,你需要安裝這兩個庫。讀取Excel文件的代碼如下:

python

import xlrd

data = xlrd.open_workbook(excelFile)

table = data.sheets()[0]

nrows = table.nrows # 行數

ncols = table.ncols # 列數

for i in range(0,nrows):

rowValues= table.row_values(i) # 某一行數據

for item in rowValues:

print(item)

寫Excel文件的代碼示例如下:

python

def WriteSheetRow(sheet,rowValueList,rowIndex,isBold):

i = 0

style = xlwt.easyxf('font: bold 1')

for svalue in rowValueList:

strValue = unicode(str(svalue),'utf-8')

if isBold:

sheet.write(rowIndex,i,strValue,style)

else:

sheet.write(rowIndex,i,strValue)

i = i + 1

def save_Excel(strFile):

excelFile = unicode(strFile, "utf8")

wbk = xlwt.Workbook()

sheet = wbk.add_sheet('sheet1',cell_overwrite_ok=True)

headList = ['標題1','標題2','標題3','標題4','總計']

rowIndex = 0

WriteSheetRow(sheet,headList,rowIndex,True)

for i in range(1,11):

rowIndex = rowIndex + 1

valueList = []

for j in range(1,5):

valueList.append(j*i)

WriteSheetRow(sheet,valueList,rowIndex,False)

wbk.save(excelFile)

在這個示例中,我們定義了WriteSheetRow函數用於寫入Excel文件,以及save_Excel函數用於保存文件。

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:645
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:936
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:632
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:821
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:731
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1066
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:299
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:160
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:852
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:763