1. 安装xlrd与xlwt模块
下载地址:xlrd(https://pypi.python.org/pypi/xlrd), xlwt(https://pypi.python.org/pypi/xlwt/1.3.0).
2. 读文件
import xlrd;
workBook = xlrd.open_workbook(u'test.xlsx');
for sheetName in workBook.sheet_names():
sheet = workBook.sheet_by_name(sheetName);
for i in range(sheet.nrows):
for j in range(sheet.ncols):
print(sheet.cell(i, j).value + '\t', end=""); # 不换行输出
print();
原始数据如图:
运行结果:
另外,可以通过 sheet.cell(i, j).ctype
获取单元格的数据类型。有六种类型,分别是:
0:空值,1:字符串,2:数字,3:日期,4:Boolean,5:异常值
3. 写文件
import xlwt;
result = xlwt.Workbook();
reSheet1 = result.add_sheet(u'Sheet1');
for i in range(5):
for j in range(5):
reSheet1.write(i, j, "row: " + str(i) + ", col:" + str(j));
result.save("test.xls"); # 注意,要保存为.xls
如图: