1.下载xlrd和xlwt
pip install xlwd
pip install xlrd
pip install xlutils
2.读写操作(已存在的excel)
#-*- coding:utf-8 -*- import xlrd from xlutils.copy import copy; #设置路径 path = u'F:\postgraduate\test.xlsx' #打开文件 data = xlrd.open_workbook(path) sheet_name = data.sheet_by_name(u'Sheet1') sheet_name.row_values(1) sheet_name.col_values(1) n_of_rows=sheet_name.nrows n_of_cols=sheet_name.ncols for i in range(n_of_rows): print sheet_name.row_values(i) # 通过坐标读取表格中的数据 cell_value1 = sheet_name.cell_value(0, 0) print cell_value1 newWb = copy(data) newWs = newWb.get_sheet(0) inserColNo = 2 newWs.write(0, inserColNo, "value1") newWs.write(1, inserColNo, "value2") newWs.write(2, inserColNo, "value3") newWb.save(path) print "save with same name ok"
3.出现的问题
可能会出现无法打开excel的情况,可能是因为excel版本过低,无法打开.xlsx
解决办法:将后缀名改为.xls即可正常打开,然后可以另存为.xlsx变回来