python 对excel交互工具的使用详情

这篇文章主要介绍了python 对excel交互工具的使用详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

python 对excel的 读入 与 改写

(对比xlwt、openpyxl、xlrd)

  • xlwt不支持写xlsx文件。
  • openpyxl不支持读xls文件。
  • 计划任务xlrd支持读xls,xlsx文件。
  • 计划任务推荐读文件用xlrd,写文件用openpyxl。
#一、xlrd 读 # 1.引入库& 下载库 xlrd pip install xlrd  	# 下载 pip show xlrd  		# 显示版本 pip install xlrd==1.2.0   # 下载指定版本 import xlrd			# 导入 workBook = xlrd.open_workbook('D:\project\info.xls', 'rb') # 打开文件 workBook = xlrd.open_workbook(r'D:\project\info.xls') allSheetNames = workBook.sheet_names()  # 获取所有sheet的名字(list类型) SheetName1= workBook.sheet_names()[0]	# 按索引号 print(allSheetNames, SheetName1) #输出: ['Sheet1', 'Sheet2', 'Sheet3'] Sheet1 # 获取sheet内容 sheet1_content1 = workBook.sheet_by_index(0) # sheet索引从0开始 sheet1_content2 = workBook.sheet_by_name('sheet1') # 按sheet名字获取 # 获取整行和整列的值(数组) print(sheet1_content1.name,sheet1_content1.nrows,sheet1_content1.ncols) # 获取整行和整列的值(数组) rows = sheet1_content1.row_values(3) # 获取第四行内容 cols = sheet1_content1.col_values(2) # 获取第三列内容 print(rows) print(cols ) # 获取单元格内容(三种方式) print(sheet1_content1.cell(1, 0).value) print(sheet1_content1.cell_value(2, 2)) print(sheet1_content1.row(2)[2].value) 

二、python 写入数据

1 、 xlwt包写入Excel文件

xlwt 写库的局限性: 只能写入新建的 excel。
(写入打开文档 可用xlutils.copy的 copy 复制一份)
xlwt中生成的xls文件最多能支持65536行数据

创建表写入数据 # 向execl中 批量写入虚假数据 import xlwt,faker,random wb=xlwt.Workbook() sheet002=wb.add_sheet("002") head=["姓名","年龄","性别"] for h in head: sheet002.write(0,head.index(h),h) #利用for 循环 挨个写入 数据 行,列,数据值 这里列使用下标即可 fake=faker.Faker() for i in  range(1,101): sheet002.write(i, 0, fake.name()) sheet002.write(i, 1, random.randint(10,60)) sheet002.write(i, 2, random.choice(['男','女'])) wb.save("002.xls")

#2 复制表写入数据 import xlwt import xlrd import xlutils.copy rd = xlrd.open_workbook("Hello.xls", formatting_info = True)   # 打开文件 wt = xlutils.copy.copy(rd)   # 复制 sheets = wt.get_sheet(0)   # 读取第一个工作表 sheets.write(m, n, "I love you!")   # 向 m-1 行 n-1 列的单元格写入内容 wt.save("Hi.xls")   # 保存

2、openpyx 只可以读xlsx 不可读xls文档

xl = openpyxl.load_workbook('D:\project\infoexcel.xlsx', data_only=True) # 设置工作表 sheet1 = xl.worksheets[0] for i in range(1, 24): sheet1.cell(i, 3).value = cvalue # 保存表格 xl.save('D:\project\infoexcel.xlsx')

三、小结

python 提供excel交互的工具包很多,

  • 一、 找到适合自己
  • 二、 区分不同包的权限与功能

如:(xlrd 新版本不支持xlsx ,需要回滚老版本才可使用)

  • 三、出现问题debug运行寻找问题点,合理尽快解决问题!

到此这篇关于python 对excel交互工具的使用详情的文章就介绍到这了,更多相关python excel交互工具 内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是python 对excel交互工具的使用详情的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python