[英]how to automate excel with python
此代碼將用其下的行長度替換所有出現的單詞“SEGMENT”,直到出現新的“SEGMENT”。
您需要使用 pip 安裝openpyxl
pip pip install openpyxl
from openpyxl import load_workbook
workbook = load_workbook(filename="yourFile.xlsx")
sheet = workbook.active
text = ""
# Iterator for row in sheet
i = 0
for x in sheet:
i += 1
# Append to text
text += str(sheet[f"A{i}"].value) + "\n"
# Iterator
i = -1
# Index of SEGMENT
j = 1
# last index of SEGMENT
k = 0
# All the values which all the SEGMENTS will be replaced through
newVars = []
for x in text.split("SEGMENT"):
# Increase the iterator
i += 1
# Append the length of vars minus 2 (The Segment before and after)
newVars.append(len(text.split("SEGMENT")[i].split("\n"))-2)
# Remove the first item (-1)
del newVars[0]
# Iterator of rows
i = 0
# Iterator of SEGMENTS
j = 0
for x in sheet:
i += 1
if sheet[f"A{i}"].value == "SEGMENT":
# Replacing the value with !{lenOfRows}
sheet[f"A{i}"].value = "!" + str(newVars[j])
# Increasing the iterator for the SEGMENTS
j += 1
# Save the file
workbook.save(filename="yourFile.xlsx")
# Just a print
print("Everything got replaced")
此代碼可以改進,但應該可以工作
注意:所有內容都必須在 Excel 文件的A
列中。
當然你需要用你的替換文件名
如果你能以.csv格式保存你的 Excel 文檔,你可以這樣做,只使用 python 的文件 i/o。
這個答案說明了您只有一列的特定問題。 對於多列,使用 python csv 庫或 openpyxl 可能更容易。
代碼假定輸入文件名為segments.csv ,它保存到一個名為output.csv的新文件中。
output = []
SEGMENT = "SEGMENT"
with open("segments.csv", 'r') as file:
lines = file.read().split()
count = 0
segment_index = -1
# fills the output with segment counts
for i, line in enumerate(lines):
if line == SEGMENT:
if segment_index != -1:
output[segment_index] = str(count)
count = 0
segment_index = i
else:
count += 1
output.append(line)
# accounts for the last segment
if segment_index != - 1:
output[segment_index] = str(count)
# writes output content to a new file
with open("output.csv", 'w') as file:
file.write('\n'.join(output))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.