Python如何读写Excel文件

Jackey Python 1,596 次浏览 , 没有评论

源数据格式:

姓名 语文 数学 外语
测试 95 99 96
张三1 90 95 91
张三2 91 96 92
张三3 92 97 93
张三4 93 98 94
张三5 94 99 95
张三6 95 100 96
张三7 96 101 97
张三8 97 102 98
张三9 98 103 99
张三10 99 104 100
张三11 100 105 101
张三12 101 106 102
张三13 102 107 103
张三14 103 108 104

输出文件格式:

姓名 语文 数学 外语 总分
测试 95 99 96 290
张三1 90 95 91 276
张三2 91 96 92 279
张三3 92 97 93 282
张三4 93 98 94 285
张三5 94 99 95 288
张三6 95 100 96 291
张三7 96 101 97 294
张三8 97 102 98 297
张三9 98 103 99 300
张三10 99 104 100 303
张三11 100 105 101 306
张三12 101 106 102 309
张三13 102 107 103 312
张三14 103 108 104 315

代码:

# 如何读写Excel文件
# 安装所需库  pip install xlrd xlwt
import xlrd, xlwt

# 支持xls,不支持xlsx
from xlwt.compat import xrange

book = xlrd.open_workbook('chengji.xls')
print(book.sheets())

sheet = book.sheet_by_index(0)
# 访问行数
print(sheet.nrows)  # 输出结果:16
# 访问列数
print(sheet.ncols)  # 输出结果:4
# 访问对应行和列数据
cell = sheet.cell(0, 0)
print(cell)  # 输出结果:text:'姓名'
# 内容的数据类型 1文本,2数字
print(cell.ctype)
# 内容
print(cell.value)

cell = sheet.cell(1, 1)
print(cell)
# 内容的数据类型 1文本,2数字
print(cell.ctype)
# 内容
print(cell.value)

# 获取一行
print(sheet.row(1))  # 输出结果:[text:'测试', number:95.0, number:99.0, number:96.0]
# 获取一行的值
print(sheet.row_values(1))  # 输出结果:['测试', 95.0, 99.0, 96.0]
# 获取一行的值, 跳过第一个
print(sheet.row_values(1, 1))  # 输出结果:[95.0, 99.0, 96.0]

nc = sheet.ncols
sheet.put_cell(0, nc, xlrd.XL_CELL_TEXT, u'总分', None)

for row in xrange(1, sheet.nrows):
    t = sum(sheet.row_values(row, 1))
    sheet.put_cell(row, nc, xlrd.XL_CELL_NUMBER, t, None)

wBook = xlwt.Workbook()
wSheet = wBook.add_sheet(sheet.name)
style = xlwt.easyxf('align: vertical center, horizontal center')
for r in xrange(sheet.nrows):
    for c in xrange(sheet.ncols):
        wSheet.write(r, c, sheet.cell_value(r, c), style)

wBook.save('output.xlsx')

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go