python之excel讀寫操做

1、xlrd和xlwt安裝

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

二、解壓後進入文件目錄

三、執行python setup.py install

2、讀取操做

 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.nrows
19 #總列數
20 ncols = sheet1.ncols
21 # 遍歷打印表中的內容
22 for i in range(nrows):
23   for j in range(ncols):
24     cell_value = sheet1.cell_value(i, j)
25 cell_str = str(cell_value).split('.')[0]  #若是excel單元格是數字,讀取後去除小數點
26 print(cell_str, end = "\t") 27 print("")

3、寫入操做

 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")

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

#!/usr/bin/python
# -*- coding: utf-8 -*-
import xlrd
import xlwt
import sys
import 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.nrows
ncols_read = sheet_read.ncols

book_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")
相關文章
相關標籤/搜索