2016-11-30 21 views
2

아래의 Python 테스트 코드를 사용하여 Excel (*.xls) 파일의 유일한 워크 시트를 하나의 워크 시트가있는 새 Excel 파일로 복사하려고합니다. 나는이 코드를 실행하면XLS의 워크 시트 만 복사하여 파이썬을 사용하는 새로운 XLS에서 새로운 워크 시트가됩니까?

enter image description here

from copy import deepcopy 
from xlrd import open_workbook 
from xlutils.copy import copy as copy 
from xlwt import Workbook 

rb = open_workbook(r"C:\Temp\test1.xls",formatting_info=True) 
wb = copy(rb) 
new_book = Workbook() 
r_sheet = rb.sheet_by_index(0) 

sheets = [] 
w_sheet = deepcopy(wb.get_sheet(0)) 
w_sheet.set_name("test1") 

for row_index in range(0, r_sheet.nrows): 
    for col_index in range(0, r_sheet.ncols): 
     cell_value = r_sheet.cell(row_index, col_index).value 
     print cell_value 
     w_sheet.write(row_index, col_index, cell_value) 

sheets.append(w_sheet) 
new_book._Workbook__worksheets = sheets 

new_book.save(r"C:\Temp\test2.xls") 

는 아래의 출력을 보여주고 새 Excel 워크 시트 이름을 TEST1으로 파일을 생성합니다 같은

입력 스프레드 시트 보인다.

Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32 
Type "copyright", "credits" or "license()" for more information. 
>>> ================================ RESTART ================================ 
>>> 
Col1 
Col2 
Col3 
a 
1.0 
X 
b 
2.0 
Y 
c 
3.0 
Z 
>>> 

불행히도, 기록 셀의 정확한 개수가 나타나는 출력은 #VALUE!로 기록 된 모든 숫자가 아닌 셀 값을 갖는다.

enter image description here

파이썬 2.7.10 사용하여, 하나의 XLS에서 워크 시트를 읽고 다음 다른 XLS 파일에 워크 시트로 작성하는 간단한 방법은 무엇입니까?

일단 스프레드 시트를 복사 한 다음 워크 시트의 이름을 바꾸려면 워크 시트를 한 번만 복사하면됩니다. 10 개의 워크 시트가있는 스프레드 시트의 이름.

+0

: 그건 당신이 같은 오류를 볼 수없는 경우

pip install pyexcel pyexcel-xls 

'.get_sheet (0)'을'.sheet_by_index (0)'로 바꿔보십시오. – Giordano

답변

3
from xlrd import open_workbook 
from xlutils.copy import copy 

# Read the workbook 
rb = open_workbook("input.xls", formatting_info=True) 

# Copy into a new workbook 
wb = copy(rb) 

# Rename to 'test1' as the original post asked for 
ws = wb.get_sheet(0) 
ws.name = 'test1' 

# Save the new workbook 
wb.save("output.xls") 
3

pyexcel을 사용해보세요. 그것은 당신이하려는 일을 훨씬 쉽게 해줄 것입니다.

12 개의 다른 통합 문서에서 하나의 시트를 사용하여 새 통합 문서를 작성해야하는 최종 요구 사항에 따라 다음은 도움이되는 몇 가지 코드입니다.

import pyexcel as pe 

outputbook = "merged.xls" 
inputbooks = { 
    "test1.xls" : "Sheet1", 
    "test2.xls" : "Sheet1", 
    "test3.xls" : "Sheet1", 
} 

merged_book = None 
for book, sheet in inputbooks.iteritems(): 
    wb = pe.get_book(file_name=book) 
    if merged_book is None: 
    merged_book = wb[sheet] 
    else: 
    merged_book = merged_book + wb[sheet] 

merged_book.save_as(outputbook) 

inputbooks은 해당 시트에 대해 읽고 싶은 통합 문서의 사전 매핑입니다.

당신은 작업중인 파일 형식되는 추가 플러그인을 따라 설치해야 할 수 있습니다 :

IOError: No suitable library found for xls