使用Python在Excel中进行字符串替换
我想把 %
符号去掉,并用一个字符串替换它;同时把空格去掉,用下划线替换。
这是我到目前为止做的:
# Open Excel file from a user imput
import xlrd, xlwt
filename = raw_input("Enter Excel file name with extension (.xls) and path")
oldbook = xlrd.open_workbook(filename)
newbook = xlwt.Workbook()
# For all the sheets in the workbook
for sheetname in oldbook.sheet_names():
oldsheet = oldbook.sheet_by_name(sheetname)
newsheet = newbook.add_sheet(sheetname)
# For all the rows and all the columns in an excel
for ii in range(oldsheet.nrows):
for jj in range(oldsheet.ncols):
# Replace
range.replace("%", "Perc")
# Save the file in a desired location with the desired name
savelocation = raw_input("Enter a new path and file name with extension (.xls) to save the new Excel spread sheet ")
newbook.save(savelocation)
1 个回答
2
有一个建议,就是把单元格的数据先读成一个字符串,然后再进行处理。
可以试试这个方法:(很遗憾我现在无法运行它)
# Open Excel file from a user imput
import xlrd, xlwt
filename = raw_input("Enter Excel file name with extension (.xls) and path")
oldbook = xlrd.open_workbook(filename)
newbook = xlwt.Workbook()
# For all the sheets in the workbook
for sheetname in oldbook.sheet_names():
oldsheet = oldbook.sheet_by_name(sheetname)
newsheet = newbook.add_sheet(sheetname)
# For all the rows and all the columns in an excel
for ii in range(oldsheet.nrows):
for jj in range(oldsheet.ncols):
# Replace
CellString=str(oldsheet.cell(ii, jj).Value)
CellString=CellString.replace("%", "Perc")
CellString=CellString.replace(" ", "_")
newsheet.write(ii, jj, CellString)
# Save the file in a desired location with the desired name
savelocation = raw_input("Enter a new path and file name with extension (.xls) to save the new Excel spread sheet ")
newbook.save(savelocation)