码迷,mamicode.com
首页 > 编程语言 > 详细

python对Excel表格操作

时间:2019-04-19 12:01:13      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:ESS   color   手机号   创建excel文件   设置   单元格   dom   xlwt   nes   

操作场景,给一个Excel表格随机生成10万个手机号码

python中常见的对Excel操作模块

xlwt module 将数据写入Excel表

xlrd module 读取Excel表格

xlsxwriter modole  xlwt模块的升级版,用于处理大量数据

先用xlwt写入Excel操作

import xlwt # 将数据写入Excel
import random


book = xlwt.Workbook(encoding=utf-8,style_compression=0) # 创建workbook对象,设置编码格式
worksheet = book.add_sheet(test,cell_overwrite_ok=True) # 创建一个sheet对象,cell_overwrite_ok表示可以覆盖单元格
worksheet.write(0,0,phone) # 在0,0位置写入phone,前面0代表列,后面0代表行

# 手机开头号码
prelist = ["130","131","132","133","134","135","136","137","138","139","147","150","151","152","153","155","156","157","158","159","186","187","188"]
nums = 0
for i in range(100000):
    # 组合成一个11位手机号码
    phones = random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))
    nums += 1
    worksheet.write(nums,0,phones)

book.save(rD:\python\test.xls)

执行后发现报错:ValueError: row index was 65536, not allowed by .xls format

原因是xlwt修改xls数据最多只能修改到65536行,所以只能使用新的模块xlsxwriter模块修改的文件是xlsx

用xlsxwriter模块修改Excel文件

import xlwt # 将数据写入Excel
import xlrd # 读取Excel文档
from xlutils.copy import copy
import xlsxwriter
import random


workbook = xlsxwriter.Workbook(rD:\python\test.xlsx) # 创建Excel文件
worksheet = workbook.add_worksheet() # 创建一个sheet,不加名字默认sheet
worksheet.write(0,0,"phone")
# 手机开头号码
prelist = ["130","131","132","133","134","135","136","137","138","139","147","150","151","152","153","155","156","157","158","159","186","187","188"]
nums = 0
for i in range(100000):
    # 组合成一个11位手机号码
    phones = random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))
    nums += 1
    worksheet.write(nums,0,phones)

workbook.close()

 

python对Excel表格操作

标签:ESS   color   手机号   创建excel文件   设置   单元格   dom   xlwt   nes   

原文地址:https://www.cnblogs.com/lumama520/p/10734894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!