Python对excel表格的操作.
参考博客:
https://blog.csdn.net/lmj19851117/article/details/78814721
####一、excel的读取操作xlrd####
import xlrd ##################一、excel的读取操作xlrd###################### data =xlrd.open_workbook(r"F:\myexcel.xls") #0.打开excel操作 table = data.sheets()[0] #通过索引顺序获取 table = data.sheet_by_index(0) #通过索引顺序获取 table = data.sheet_by_name(u'Sheet1')#通过名称获取 #1. 获取excel sheet对象 table1 =data.sheets()[0] table2=data.sheet_by_index(0) table3=data.sheet_by_name(U"Sheet1") print(table1) print(table2) print(table3)
输出结果:
<xlrd.sheet.Sheet object at 0x00000131D1B1BCF8>
<xlrd.sheet.Sheet object at 0x00000131D1B1BCF8>
<xlrd.sheet.Sheet object at 0x00000131D1B1BCF8>
#2. 获取sheet的行与列数量. rows=table1.nrows col =table1.ncols print("行数为%s \n列数为%s"%(rows,col))
输出结果:
行数为14
列数为9
#3. 获取整行和整列的数据. row =table1.row_values(0) col =table1.col_values(2) print(row) print(col)
输出结果
['A', 'sheet', 'sheet', 'sheet', 'sheet', 'sheet', 'sheet', 'sheet', 'sheet']
['sheet', 1.0, 3.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0]
#4.获取单元格数据 cell_a1 =table1.cell_value(0,0) cell_x =table1.cell_value(2,3) #(第三行,第四列数据) print(cell_a1) print(cell_x)
输出结果:
A
4.0
####二、excel的写操作xlwt#####
#0.导入xlwt import xlwt #1.创建workbook对象 workbook =xlwt.Workbook(encoding ="utf-8",style_compression=0) #2.创建一个sheet对象,一个sheet对象对应excel文件中一张表格. sheet =workbook.add_sheet("2",cell_overwrite_ok=True) #Cell_overwirte_ok 是能够覆盖单元表格的意思。 print(sheet)
<xlwt.Worksheet.Worksheet object at 0x00000131D1C3E710>
#3.向表中添加数据. # sheet.write(0,0,"english_name111111111111") # sheet.write(1,0,"helloworld") # # #4.保存. workbook.save(r"2")
总结: python 操作excel
import xlrd ##################一、excel的读取操作xlrd###################### data =xlrd.open_workbook(r"F:\myexcel.xls") #0.打开excel操作 table = data.sheets()[0] #通过索引顺序获取 table = data.sheet_by_index(0) #通过索引顺序获取 table = data.sheet_by_name(u'Sheet1')#通过名称获取 #1. 获取excel sheet对象 table1 =data.sheets()[0] table2=data.sheet_by_index(0) table3=data.sheet_by_name(U"Sheet1") print(table1) print(table2) print(table3) #2. 获取sheet的行与列数量. rows=table1.nrows col =table1.ncols print("行数为%s \n列数为%s"%(rows,col)) #3. 获取整行和整列的数据. row =table1.row_values(0) col =table1.col_values(2) print(row) print(col) #4.获取单元格数据 cell_a1 =table1.cell_value(0,0) cell_x =table1.cell_value(2,3) #(第三行,第四列数据) print(cell_a1) print(cell_x) ##################二、excel的写操作xlwt###################### #0.导入xlwt import xlwt #1.创建workbook对象 workbook =xlwt.Workbook(encoding ="utf-8",style_compression=0) #2.创建一个sheet对象,一个sheet对象对应excel文件中一张表格. sheet =workbook.add_sheet("2",cell_overwrite_ok=True) #Cell_overwirte_ok 是能够覆盖单元表格的意思。 print(sheet) #3.向表中添加数据. # sheet.write(0,0,"english_name111111111111") # sheet.write(1,0,"helloworld") # # #4.保存. workbook.save(r"2")