2014-03-27 4 views
3

xls 및 csv 모듈과 함께 Python 3.3을 사용하여 xls 파일을 csv로 변환합니다. 그와xlrd를 사용하여 Python 3에서 xls를 csv로 변환

import xlrd 
import csv 

def csv_from_excel(): 

    wb = xlrd.open_workbook('MySpreadsheet.xls') 
    sh = wb.sheet_by_name('Sheet1') 
    your_csv_file = open('test_output.csv', 'wb') 
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL) 

    for rownum in range(sh.nrows): 

     wr.writerow(sh.row_values(rownum)) 

    your_csv_file.close() 

나는이 오류 받고 있어요 : TypeError: 'str' does not support the buffer interface

내가 인코딩을 변경 시도하고 이와 루프 내에서 라인을 교체 :

wr.writerow(bytes(sh.row_values(rownum),'UTF-8')) 

하지만 수를이 내 코드입니다 이 오류 : TypeError: encoding or errors without a string argument

무엇이 잘못 될지 알고 있습니까?

답변

3

은 내가

import pandas as pd 
xls = pd.ExcelFile('file.xlsx') 
df = xls.parse(sheetname="Sheet1", index_col=None, na_values=['NA']) 
df.to_csv('file.csv') 
+0

또는 더 짧게 :'df = pd.read_excel (...)' – user2146414

1

귀하의 문제는 당신이 Python2 의미로 파일을 열어야 기본적으로이 작업 pandas 라이브러리를 사용하는 것이 좋습니다. Python3 로케일 인식, 그래서 당신은 단지이 파일에 텍스트를 쓰고 싶어 (그리고 당신이 할) 경우, 올바른 옵션이 포함 된 텍스트 파일로 엽니 다

your_csv_file = open('test_output.csv', 'w', encoding='utf-8', newline='')

인코딩 매개 변수는 출력 인코딩을 지정합니다 (utf-8 일 필요는 없습니다) csv에 대한 Python3 문서에는 csv 파일 객체에 newline=''을 지정해야한다고 명시되어 있습니다.

2

pandas와 함께 할이

import xlrd 
import csv 

def csv_from_excel(): 
    wb = xlrd.open_workbook('MySpreadsheet.xlsx') 
    sh = wb.sheet_by_name('Sheet1') 
    your_csv_file = open('output.csv', 'w', encoding='utf8') 
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL) 

    for rownum in range(sh.nrows): 
     wr.writerow(sh.row_values(rownum)) 

    your_csv_file.close() 
0

빠른 방법을 시도해보십시오

import pandas as pd 

xls_file = pd.read_excel('MySpreadsheet.xls', sheetname="Sheet1") 
xls_file.to_csv('MySpreadsheet.csv', index = False) 
#remove the index because pandas automatically indexes the first column of CSV files. 

당신은 pandas.read_excel here에 대한 자세한 내용을보실 수 있습니다.

관련 문제