使用Python在Excel中替换字符串

时间:2014-03-27 16:28:22

标签: python excel python-2.7

我想删除%并替换为字符串,并删除空格并将其替换为低分。

这是我到目前为止所做的:

# 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 个答案:

答案 0 :(得分:1)

一个建议,将单元格数据读入字符串然后进行操作。

试试这个:(不幸的是我现在无法运行它)

# 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)
相关问题