![](/img/trans.png)
[英]How to import an XML file into an Excel XLS file template using Python?
[英]How to search and replace string in excel (.xls) file using Python?
我正在嘗試在 excel 文件(xls)中使用搜索和替換字符串,實際上 - 我需要在前綴 * 之前找到字符串並添加。 例如
但我收到一個錯誤:
LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced}
NameError: name 'two_replaced' is not defined
代碼:
from xlrd import open_workbook
from xlutils.copy import copy
import xlsxwriter
rb = open_workbook("template.xlsx")
# Create an new Excel file and add a worksheet.
wb = xlsxwriter.Workbook('Updated_Workbook1.xlsx')
ws = wb.add_worksheet()
s_orig = rb.sheet_by_index(0)
LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}
for row in range(s_orig.nrows):
for col in range(s_orig.ncols):
if s_orig.cell(row,col).value in LVdemact:
# s.write(row, col, LVdemact[item])
ws.write(row, col, LVdemact[s_orig.cell(row,col).value])
else:
ws.write(row, col, s_orig.cell(row,col).value)
wb.close()
問題出在一行 - LVdemact = {'two': two_replaced, 'six': six_replaced, 'five': five_replaced,}
變量two_replaced
、 six_replaced
和five_replaced
未定義。 你希望這是一個字符串嗎? 然后以這種方式定義它 -
LVdemact = {'two': 'two_replaced', 'six': 'six_replaced', 'five': 'five_replaced'}
你可以用這個
df = pd.DataFrame() # Your dataframe
for column in df.select_dtypes('object'):
df[column] = df[column].str.replace('toreplace','newword')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.