報錯:ValueError: row index was 65536, not allowed by .xls formatpython
讀取.xls文件正常,在寫.xls文件,pd.to_excel()時候會報錯函數
緣由:寫入的文件行數大於65536excel
Pandas 讀取 Excel 文件的引擎是 xlrd ,xlrd 雖然同時支持 .xlsx 和 .xls 兩種文件格式,可是在源碼文件 xlrd/sheet.py 中限制了讀取的 Excel 文件行數必須小於 65536,列數必須小於 256。orm
xlrd和xlwt處理的是xls文件,單個sheet最大行數是65535,若是有更大須要的,建議使用openpyxl函數,最大行數達到1048576。
若是數據量超過65535就會遇到:ValueError: row index was 65536, not allowed by .xls formatblog
解決:get
方法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 ,再讀取文件就能夠了。pandas
import pandas as pd df = pd.read_excel(‘./data.xlsx’, engine=’openpyxl’) pd.write( ,engine=’openpyxl’)