excel数据操作

要想通过python网excel中写数据,就必须先安装xlwt

  安装命令:pip install xlwt

一:写入excel

1.创建一个工作簿

book = xlwt.Workbook()

2.创建一个工作表

sheet = book.add_sheet("Test")

3.添加数据

sheet.write(0,0,"id") 参数一:excel行数,参数二:excel列数,参数三:写入的数据
sheet.write(0,1,"name")
sheet.write(1,0,"1")
sheet.write(1,1,"倩倩")

4.保存

book.save("excel文件名称")

二:读取excel:

1.打开一个excel对象

book = xlrd.open_workbook("exce文件名称")

2.获取一个sheet文件

sheet=book.sheet_by_name("excel文件名称") //如果知道是哪个文件直接传入文件名称即可
sheet = book.sheet_by_index(文件所在的索引) //根据索引获取excel中sheet文件

3.获取文件内容

sheet.cell(0,0).value //参数一:第几行,参数二:第几列  values:获取内容 
#获取一整行所有的数据
sheet.row_values(int) //获取一整行的数据 参数:行号
#获取某一列所有的数据
sheet.col.values(int) //获取一整列的数据 参数:列好

其他操作:

book.sheets() //获取excel中所有sheet对象
sheet.nrows() //获取一共有多少行
sheet.ncols() //一共有多少列

获取某个文档的所有数据
book = xlrd.open_workbook("aaa.xls")
sheet = book.sheet_by_name("bbb")
row = sheet.nrows
col = sheet.ncols
for r in range(row):
  for c in range(col):
    print(sheet.cell(r, c).value, end=",")
r += 1
print()
原文地址:https://www.cnblogs.com/zhangwei-qianqian/p/14061231.html