2017-05-12 156 views
0

我想從一個excel文件中只複製特定行到另一個使用python。 temp_list只有我想要複製的行號。但它似乎是複製所有行。我在這裏做錯了什麼?Python程序只複製excel文件中的特定行復制所有行

import xlrd 
book = xlrd.open_workbook("file.xlsx") 
sheet = book.sheet_by_index(0) 
temp_list = [1,4,5,6,7,8,9,10,15,19,26] 
book1 = copy(book) 
sheet1=book1.get_sheet(0) 
totalcols=sheet.ncols 
k=0 

for j in temp_list: #for rows 
    for i in range(0,totalcols): 
     try: 
      value=sheet.cell_value(j,i) 

      sheet1.write(k,i,value) 
     except IndexError: 
      continue 
    k=k+1 
book1.save("Gibberish_Removed.xls") 
+0

您將該書複製到book1。你不想創建一個新的空白書,而不是調用'copy(book)' – MaxNoe

回答

0

這個問題似乎是在

book1 = copy(book) 
sheet1 = book1.get_sheet(0) 

然後

sheet1.write(chosen_values) #chosen value is value at index, (k,i) 

這將只是簡單地覆蓋所選擇的值(K,I),但因爲你的複製工作表Sheet1書,它也會有其他行。 您需要以空白工作表1開頭。

0

我認爲你應該使用「xlwt」包裝來寫作。

import xlrd 
from xlwt import Workbook 

book = xlrd.open_workbook("file.xlsx") 
sheet = book.sheet_by_index(0) 
temp_list = [1, 4, 5, 6, 7, 8, 9, 10, 15, 19, 26] 
book1 = Workbook() 
sheet1 = book1.add_sheet('test', cell_overwrite_ok=True) 
total_cols = sheet.ncols 
k = 0 
for j in temp_list: #for rows 
    for i in range(0, total_cols): 
     value = sheet.cell_value(j-1,i) 
     sheet1.write(k, i, value) 
    k += 1 
book1.save("Gibberish_Removed.xls")