栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python读写excel文件示例

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python读写excel文件示例

参考python读取excel中的数据
参考Python:数据导出到Excel(使用xlwt)

一、python利用xlrd库读excel数据(xlsx) 注意:新版(2.0.1)xlrd不支持xlsx,这里利用1.2.0版的xlrd

pip uninstall xlrd
pip install xlrd==1.2.0

具体python代码:
import xlrd

workBook = xlrd.open_workbook('C:/Users/win10/Desktop/catchData/testData.xlsx')
# 1.获取sheet的名字
# 1.1 获取所有sheet的名字(list类型)
allSheetNames = workBook.sheet_names()
print(allSheetNames)

# 1.获取sheet的名字
# 1.1 获取所有sheet的名字(list类型)
allSheetNames = workBook.sheet_names();
print(allSheetNames);

# 1.2 按索引号获取sheet的名字(string类型)
sheet1Name = workBook.sheet_names()[0];
print(sheet1Name);

# 2. 获取sheet内容
## 2.1 法1:按索引号获取sheet内容
sheet1_content1 = workBook.sheet_by_index(0); # sheet索引从0开始
## 2.2 法2:按sheet名字获取sheet内容
sheet1_content2 = workBook.sheet_by_name('Sheet1');

# 3. sheet的名称,行数,列数
print(sheet1_content1.name,sheet1_content1.nrows,sheet1_content1.ncols);

# 4. 获取整行和整列的值(数组)
rows = sheet1_content1.row_values(3); # 获取第四行内容
cols = sheet1_content1.col_values(2); # 获取第三列内容
print(rows);

# 5. 获取单元格内容(三种方式)
print(sheet1_content1.cell(1, 0).value);
print(sheet1_content1.cell_value(2, 2));
print(sheet1_content1.row(2)[2].value);

# 6. 获取单元格内容的数据类型
# Tips: python读取excel中单元格的内容返回的有5种类型 [0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error]
print(sheet1_content1.cell(1, 0).ctype);
二、python利用xlwt库写excel数据(xls文件) python安装xlwt库

pip install xlwt

注意: 如果文件后缀为xlsx,excel可能打不开,建议后缀为xls, 生成文件后可以再转化,具体python代码:
import xlwt
excle_path = 'C:\Users\RJZhang\Desktop\resData1.xls'
# 创建一个Workbook模块
data = xlwt.Workbook(encoding='utf-8')
# 创建一个表格,cell_overwrite_ok=True 为不覆盖表,默认为False
sheet = data.add_sheet('test123',cell_overwrite_ok=True)
# 写入坐标为(0,0)内容为职位
sheet.write(0,0,'职位')
# 写入坐标为(1,0)内容为软件测试工程师
sheet.write(1,0,'软件测试工程师')
# 保存到excel中
data.save(excle_path)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/715463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号