2014-03-27 44 views
0

我想刪除%並用字符串替換和刪除空間,並根據分數與更換。字符串替換在Excel中使用Python

這是我迄今所做的:

# 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) 

回答

0

一個建議,請閱讀單元的數據轉換成字符串,然後操縱它。

試試這個:(可惜我不能在此刻運行)

# 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) 
+0

我跑的代碼,你說什麼都沒有發生。我沒有得到一個錯誤,但值whwere沒有更換 – user256683

+0

所以,你得到只是一個電子表格的副本? – hstay

+0

是我與格式化爲字符串的所有我的號碼的電子表格,但他們都沒有改變....百分比仍然符號和空的空間在Excel中不與下劃線的埋入。 – user256683