[英]Read in .xlsx with csv module in python
我正在嘗試使用csv
模塊讀取 .xlsx 格式的 excel 文件,但是即使指定了我的方言和編碼,在使用 excel 文件時我也沒有任何運氣。 下面,我用我嘗試過的不同編碼展示了我的不同嘗試和錯誤結果。 如果有人能指出我可以用來在 Python 中讀取 .xlsx 文件的正確編碼、語法或模塊,我將不勝感激。
使用以下代碼,我收到以下錯誤: _csv.Error: line contains NULL byte
#!/usr/bin/python
import sys, csv
with open('filelocation.xlsx', "r+", encoding="Latin1") as inputFile:
csvReader = csv.reader(inputFile, dialect='excel')
for row in csvReader:
print(row)
使用以下代碼,我收到以下錯誤: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcc in position 16: invalid continuation byte
#!/usr/bin/python
import sys, csv
with open('filelocation.xlsx', "r+", encoding="Latin1") as inputFile:
csvReader = csv.reader(inputFile, dialect='excel')
for row in csvReader:
print(row)
當我在encoding
使用utf-16
時,出現以下錯誤: UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 570-571: illegal UTF-16 surrogate
您不能使用 Python 的csv
庫來讀取xlsx
格式的文件。 您需要安裝和使用不同的庫。 例如,您可以按如下方式使用openpyxl
:
import openpyxl
wb = openpyxl.load_workbook("filelocation.xlsx")
ws = wb.active
for row in ws.iter_rows(values_only=True):
print(row)
這會將文件中的所有行顯示為行值列表。 Python Excel網站提供了其他可能的示例。
或者,您可以創建一個行列表:
import openpyxl
wb = openpyxl.load_workbook("filelocation.xlsx")
ws = wb.active
data = list(ws.iter_rows(values_only=True))
print(data)
注意:如果您使用舊的 Excel 格式.xls
,則可以改用xlrd
庫。 但這不再支持.xlsx
格式。
import xlrd
workbook = xlrd.open_workbook("filelocation.xlsx")
sheet = workbook.sheet_by_index(0)
data = [sheet.row_values(rowx) for rowx in range(sheet.nrows)]
print(data)
這是一個僅使用標准庫的非常粗略的實現。
def xlsx(fname, sheet=1):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet%s.xml' % sheet)):
if el.tag.endswith('}v'): # <v>84</v>
value = el.text
if el.tag.endswith('}c'): # <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
column_name = ''.join(x for x in el.attrib['r'] if not x.isdigit()) # AZ22
row[column_name] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
(這是從已刪除的問題中復制的: https : //stackoverflow.com/questions/4371163/reading-xlsx-files-using-python )
這是一個僅使用標准庫的非常粗略的實現。
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # <v>84</v>
value = el.text
if el.tag.endswith('}c'): # <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
此答案復制自已刪除的問題: https : //stackoverflow.com/a/22067980/131881
您不能使用 Python 的 csv 庫來讀取 .xlsx 格式的文件。 您也不能使用“pd.read_excel”,這是一種諷刺(它僅支持 .xls)。 下面是我創建的用於導入 .xlsx 的函數。 它在您導入的文件的第一行分配列名稱。 很直接。
def import_xlsx(filepath):
wb=openpyxl.load_workbook(filename=filepath, data_only=True)
ws = wb.active
df = list(ws.iter_rows(values_only=True))
new=pd.DataFrame(data=df)
new1=new[1:]
new1.columns=new[0:1].values[0].tolist()
return(new1)
例子:
new_df=import_xlsx('C:\\Users\big_boi\\documents\\my_file.xlsx')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.