Recently wrote a reptile, climb down the data into Excel, most started using xlwt and xlrd these two modules with the use of Excel to create and write and append operation, but there is a downside is the data about more than 65,000 of the error will
Error:
ValueError: row index was 65536, not allowed by .xls format
Solution:
xlrd and xlwt deal with xls files. The maximum number of lines in a single sheet is 65535. If there is a larger need, it is recommended to use the openpyxl function. The maximum number of lines reaches 1048576.
If the amount of data exceeds 65535, you will encounter: ValueError: row index was 65536, not allowed by .xls format
So I have to use the openpyxl module, it is recommended, because I feel that the font is more beautiful, and the performance seems to be improved.
1: Install openpyxl
pip install openpyxl
2: Write operation
#openpyxl写数据
import openpyxl #导入openpyxl模块
wb = openpyxl.Workbook() #创建空的Excel文件
sheet = wb.active #获取工作簿的活动表,通常是第一个工作表
sheet.title = '高管' #给工作表命名
#这个可以理解是表头
sheet['A1'] = '公司名称'
sheet['B1'] = '姓名'
sheet['C1'] = '职务'
sheet['D1'] = '学历'
sheet['E1'] = '薪酬'
sheet['F1'] = '持股'
sheet['G1'] = '年龄'
sheet['H1'] = '任期'
#单行数据的写入
row = ['写入','读取','模块'] #创建一个列表用以批量写入
sheet.append(row) #append将数据写入单元格中
#多行数据的写入,以列表进行分开,最后写入大列表
rows = [['写入','读取','模块'],['怪物','格格不入','同类', '经典','人物']]
for i in rows:
sheet.append(i) #遍历rows,同时把遍历的内容添加到表格里,这样就实现了多行写入。
wb.save('高管.xlsx') #保存新建的Excel文件,并命名为“测试.xlsx”
3: Existing excel sheet to append data
# 导入模块
import openpyxl
# 已存在的Excel文件的路径,根据需要修改路径
filepath = '高管.xlsx'
wb = openpyxl.load_workbook(filepath)
ws = wb['高管']
# 创建文件的时候title名字 sheet.title = '高管' 必须要对应,忘记了请看上面
# 或者你还可以 print(wb.sheetnames) 把所有子表的名字并打印出来
ws = wb['sheet2']
#待填充数据
data = [[1,2,3],[4,5,6]]
for x in data:
ws.append(x)
savename = 'update_excel.xlsx' #保存路径你可以写新路径,当然也可以写创建文件的路径,数据会追加进去
wb.save(savename)