2017-05-12 1 views
0

파이썬을 사용하여 특정 행을 다른 Excel 파일로 복사하려고합니다. temp_list에는 복사 할 행 번호 만 있습니다. 그러나 모든 행을 복사하는 것처럼 보입니다. 여기서 내가 뭘 잘못하고 있니?모든 행을 복사하는 Excel 파일에서 특정 행만 복사하는 Python 프로그램

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

문제는 (I, K)이 단지에 선택한 값을 덮어 쓰게됩니다 다음

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

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

것 같다, 하지만 당신은에서 시트 1을 복사하기 때문에 도서, 그것은 다른 행뿐만 아니라 것입니다. 빈 시트 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") 
관련 문제