python之excel讀寫操作

來源:互聯網
上載者:User

標籤:資料   獲得   文檔   setup.py   from   ESS   strong   range   索引   

一、xlrd和xlwt安裝

1、下載xlwt安裝包https://pypi.org/project/xlwt/#files

2、解壓後進入檔案目錄

3、執行python setup.py install

二、讀取操作

 1 # -*- conding:utf-8 -*- 2 __author__ = ‘dsh‘ 3 # How to read from an Excel using xlrd module 4 import xlrd 5 # 關聯指定路徑中的xls檔案,得到book對象 6 file_name = "name.xls" 7 #開啟指定檔案,建立檔案對象 8 book = xlrd.open_workbook(file_name) 9 # 通過sheet索引獲得sheet對象10 sheet1 = book.sheet_by_index(0)11 # # 獲得指定索引的sheet名12 # sheet1_name = book.sheet_names()[0]13 # print(sheet1_name)14 # # 通過sheet名字獲得sheet對象15 # sheet1 = book.sheet_by_name(sheet1_name)16 # 獲得行數和列數17 # 總行數18 nrows = sheet1.nrows19 #總列數20 ncols = sheet1.ncols21 # 遍曆列印表中的內容22 for i in range(nrows):23   for j in range(ncols):24     cell_value = sheet1.cell_value(i, j)25     print(cell_value, end = "\t")26   print("")

三、寫入操作

 1 # -*- conding:utf-8 -*- 2 __author__ = ‘dsh‘ 3 #How to write to an Excel using xlwt module 4 import xlwt 5 #建立一個Wordbook對象,相當於建立了一個Excel檔案 6 book = xlwt.Workbook(encoding = "utf-8", style_compression = 0) 7 #建立一個sheet對象,一個sheet對象對應Excel檔案中的一張表格 8 sheet = book.add_sheet("sheet1", cell_overwrite_ok = True) 9 #向表sheet1中添加資料10 sheet.write(0, 0, "EnglishName") #其中,"0, 0"指定表中的儲存格,"EnglishName"是向該儲存格中寫入的內容11 sheet.write(1, 0, "MaYi")12 sheet.write(0, 1, "中文名字")13 sheet.write(1, 1, "螞蟻")14 #最後,將以上操作儲存到指定的Excel檔案中15 book.save("name.xls")

四、實名制文檔格式轉換讀寫案例

#!/usr/bin/python# -*- coding: utf-8 -*-import xlrdimport xlwtimport sysimport os__author__ = ‘dsh‘file_name = "1111.xls"book_read = xlrd.open_workbook(file_name)sheet_read = book_read.sheet_by_index(0)nrows_read = sheet_read.nrowsncols_read = sheet_read.ncolsbook_write = xlwt.Workbook(encoding = "utf-8",style_compression = 0)sheet_write = book_write.add_sheet("sheet1",cell_overwrite_ok = True)#把第0列寫到第1列for i in range(nrows_read):    cell_value = sheet_read.cell_value(i,0)    sheet_write.write(i,1,cell_value)#把第10列資料寫到第3列for i in range(nrows_read):    cell_value = sheet_read.cell_value(i,10)    sheet_write.write(i,3,cell_value)book_write.save("2222.xls")

 

python之excel讀寫操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.