python操作Excel

import xlrd
import xlwt

 import xlutils

 import win32com


#xlrd

#打開excel

data = xlrd.open_workbook("I+P.xls")

#查看文件中包含sheet的名稱

sheetNames = data.sheet_names()

#得到第一個工作表,或者通過索引順序或工作表名稱

firstTable = data.sheets()[0]

firstTable1 = data.sheet_by_index(0)

# print firstTable

# print firstTable1

#獲取行數和列數

nrows = firstTable.nrows

ncols = firstTable.ncols

# print nrows,ncols

#獲取正行或整列的值(數組)

test1 = firstTable.row_values(1)

test2 = firstTable.col_values(1)


# print test1,test2


#單元格

cell_A1 = firstTable.cell(0,0).value

cell_C4 = firstTable.cell(2,3).value

#

# print cell_A1

# print cell_C4


#分別使用行列索引

cell_A1 = firstTable.row(0)[0].value

cell_A2 = firstTable.col(1)[0].value


print cell_A1

print cell_A2


# #xlwt

# #新建一個excel文件

# file = xlwt.Workbook()

# #新建一個sheet

# table = file.add_sheet("yanshan",cell_overwrite_ok=True)

# #cell_overwirte_ok參數控制單元格是否能夠重寫

# #寫入數據table.wirte(行,列,value)

# table.write(0,1,"yanshan")

# table.write(0,0,"test")

# table.write(1,1,"jialing")

# table.write(1,2,u"知青")

#

# #另外,可以使用style

# style = xlwt.XFStyle()#初始化樣式

# font = xlwt.Font()#爲樣式創建字體

# font.name = "Times New Roman"

# font.bold = True

# style.font = font#爲樣式設置字體

# table.write(5,5,"some bold Times text",style)

#

# #保存文件

# file.save("demo.xls")


# #xlutils,具體操作實例

# from xlrd import open_workbook

# from xlutils.copy import copy

#

# rb = open_workbook(u"I+P.xls", formatting_info=True)

# #參數formatting_info=True帶格式拷貝

# wb = copy(rb) #經過copy後得到的wb就是可寫的Workbook對象了

# #注:不支持圖片拷貝,且支持的顏色種類較少

# #對其進行寫操作

# ws = wb.get_sheet(2)

# ws.write(2, 0, "changed!")

#

# wss = wb.add_sheet("1223", 1)

# wss.write_merge(2, 2, 0, 5, "changed!")

# # wss.wirte(2, 0, "123")

#

# wb.save("I+P.xls")


#win32com

# 調用com組件操作Excel,大部分函數調用類似VBA(可查看VBA幫助文檔)

# 操作步驟:

# 連接COM庫


xlsApp = win32com.cllient.Dispatch("Excel.Application")

xlsApp = win32com.client.DispatchEx("Excel.Application")


#區別:DispatchEx新建一個Excel進程

#創建表(或打開)

book = xlsApp.Workbooks.Open(filename)

#新建

book = xlsApp.Workbooks.Add()

#獲取頁籤

sheet = book.Wooksheets(n) #n爲名字或索引

#添加頁籤

sheet = book.Wooksheets.Add(name)

#頁籤句柄屬性

sheet.name

#刪除頁籤

Worksheets(n).Delete()

#單元格賦值

sheet.Cells(r,c).Value

#保存工作表

book.Save()

book.SaveAs(filename)

#關閉工作表

books.Close(SaveChange  =  False)

#關閉COM組件

xlsApp.Application.Quit()

del xlsApp


#刪除行/列

sheet.Rows(r).Delete

sheet.Columns(r).Delete

#設置所有行/列高

sheet.Rows.RowsHeigh

sheet.Columns.ColumnWidth

#Excel拷貝對象:

sheet1.copy(sheet2) #頁籤拷貝

Range1.copy(Range2) #範圍拷貝


#多線程操作Excel使用的特殊函數(動態鏈接):

pythoncom.CoInitialize() #開闢套件

pythoncom.CoUnInitialize()  #回收套件


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章