ValueError: row index was 65536, not allowed by .xls format


報錯:ValueError: row index was 65536, not allowed by .xls format

 

讀取.xls文件正常,在寫.xls文件,pd.to_excel()時候會報錯

 

原因:寫入的文件行數大於65536

 

Pandas 讀取 Excel 文件的引擎是 xlrd ,xlrd 雖然同時支持 .xlsx 和 .xls 兩種文件格式,但是在源碼文件 xlrd/sheet.py 中限制了讀取的 Excel 文件行數必須小於 65536,列數必須小於 256。

 

xlrd和xlwt處理的是xls文件,單個sheet最大行數是65535,如果有更大需要的,建議使用openpyxl函數,最大行數達到1048576。
如果數據量超過65535就會遇到:ValueError: row index was 65536, not allowed by .xls format

 

解決:

方法1: 直接使用openpyxl

import openpyxl

def readExel():
    filename = r'D:\test.xlsx'
    inwb = openpyxl.load_workbook(filename)  # 讀文件
    sheetnames = inwb.get_sheet_names()  # 獲取讀文件中所有的sheet,通過名字的方式
    ws = inwb.get_sheet_by_name(sheetnames[0])  # 獲取第一個sheet內容

    # 獲取sheet的最大行數和列數
    rows = ws.max_row
    cols = ws.max_column
    for r in range(1,rows):
        for c in range(1,cols):
            print(ws.cell(r,c).value)
        if r==10:
            break

def writeExcel():
    outwb = openpyxl.Workbook()  # 打開一個將寫的文件
    outws = outwb.create_sheet(index=0)  # 在將寫的文件創建sheet
    for row in range(1,70000):
        for col in range(1,4):
            outws.cell(row, col).value = row*2  # 寫文件
        print(row)
    saveExcel = "D:\\test2.xlsx"
    outwb.save(saveExcel)  # 一定要記得保存

方法2:Pandas 的 read_excel 方法中,有 engine 字段,可以指定所使用的處理 Excel 文件的引擎,填入 openpyxl ,再讀取文件就可以了。

import pandas as pd

df = pd.read_excel(‘./data.xlsx’, engine=’openpyxl’)  

pd.write( ,engine=’openpyxl’)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM