它首先取決於您用來訪問Excel的Python模塊。如果您使用的是Windows,我會推薦使用可以找到的Win32Com here.該模塊提供對任何Microsoft Office應用程序(包括Excel)的Python編程訪問,並使用許多與VBA中使用的方法相同的方法。
下面是使用Win32Com for Excel解決您的問題的方法。我假設您使用逗號(',')作爲名稱之間的分隔符,並且列A和列B之間的名稱匹配區分大小寫(請記住,在Python中,「A」不等於「a」)
開始,我們希望與你們的名字
#First we need to access the module that lets us connect to Excel
import win32com.client
# Next we want to create a variable that represents Excel
app = win32com.client.Dispatch("Excel.Application")
# Lastly we will assume that the sheet with the names is the active sheet
sheet = app.ActiveSheet
連接到Excel和獲得訪問表在這一點上,我們有一個變量命名紙表示積極練成工作表與名稱。您只需點擊任何單元格即可激活工作表。現在我們首先獲得列A中的所有名稱並將其存儲到列表中。我們有這樣做的兩個選項:
- 我們可以遍歷所有單元格的列A,並提取名稱保存爲一個字符串,並將其追加到使用sheet.Cells所有名的列表(行,COL).value的。這適用於較小的範圍,但如果您處理的行數超過500行,則速度可能會變慢。
- 我們可以使用sheet.Range(「A1」,「A3」)。Value提取列A中包含名稱的整個單元格範圍,並將值添加到列表中。如果你有大量的單元格,這可以更快。對於這個例子,我們將使用Range。
例續:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet
# rang is an object representing the cells A1, A2, A3
rang = sheet.Range("A1","A3")
# names is a tuple of length 3 containing tuples of length 2
names = rang.Value
#nameLst is a list of all values in names
nameLst = [name[0] for name in names]
接下來我們要遍歷所有B列的名字爲此,我們將使用sheet.Cells.Value函數獲取Col B中每個單元格的名稱列表。我們還將使用string.split(「,」)函數將逗號分隔的名稱拆分爲一個名稱列表和string.strip()來刪除任何不必要的空格。如果有任何此列表中的名字都是在nameLst,我們知道我們有一個比賽,並把它放在上校C.
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet
rang = sheet.Range("A1","A3")
names = rang.Value
nameLst = [name[0] for name in names]
#Iterate over the rows ic ColB. Remember Excel uses base 1 not 0 for inexing
for rowI in range(1,3):
cellNames = sheet.Cells(rowI,2).Value
#split cellNames by "," and add all of the names to a list.
cellNamesLst = [cellName.strip() for cellName in cellNames.split(",")]
#Now we want a list of all names that are in cellNamesLst and in nameLst
matchLst = [matchName for matchName in cellNamesLst if matchName in nameLst]
#Create a string of all matches to go in Col C
allMatches = ", ".join(matchLst)
#Lastly put all matches in in Col C
sheet.Cells(rowI,3).Value = allMatches
這將將會把字符串「鮑勃」到單元格C1和「丹,布賴恩「進入單元格C2。 win32com的使用非常強大,可以用來自動執行你在所有MS Office應用程序中所做的大部分工作。
這裏是最後的代碼W/O評論:
import win32com.client
app = win32com.client.Dispatch("Excel.Application")
sheet = app.ActiveSheet
rang = sheet.Range("A1","A3")
names = rang.Value
nameLst = [name[0] for name in names]
for rowI in range(1,3):
cellNames = sheet.Cells(rowI,2).Value
cellNamesLst = [cellName.strip() for cellName in cellNames.split(",")]
matchLst = [matchName for matchName in cellNamesLst if matchName in nameLst]
allMatches = ", ".join(matchLst)
sheet.Cells(rowI,3).Value = allMatches
希望這有助於。
你有什麼試過? 這可能是一個開始的地方:http://packages.python.org/openpyxl/ – deadly 2012-08-13 12:24:32
@gene onyx:你沒有評論我的答案或在這裏,你找到了答案?如果是這樣,你可以關閉這個問題嗎? – 2012-08-13 13:56:36
感謝上述鏈接致命。這麼多一次採取一切。 – Onyx 2012-08-14 09:20:38