Python *** 作Excel,怎么插入一行或一列

Python  *** 作Excel,怎么插入一行或一列,第1张

就是把插入行之后值重新如或输出来。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

import xlwt

import xlrd

from xlutils.copy import copy

#styleBoldRed = xlwt.easyxf('font: color-index red, bold on')

#headerStyle = styleBoldRed

#wb = xlwt.Workbook()

#ws = wb.add_sheet('sheetName')

#ws.write(0, 0, "Col1",headerStyle)

#ws.write(0, 1, "Col2", headerStyle)

#ws.write(0, 2, "Col3"胡橡模,headerStyle)

#wb.save('fileName.xls'裤缓)

#open existed xls file

oldWb = xlrd.open_workbook("fileName.xls", formatting_info=True)

oldWbS = oldWb.sheet_by_index(0)

newWb = copy(oldWb)

newWs = newWb.get_sheet(0)

inserRowNo = 1

newWs.write(inserRowNo, 0, "value1")

newWs.write(inserRowNo, 1, "value2")

newWs.write(inserRowNo, 2, "value3")

for rowIndex in range(inserRowNo, oldWbS.nrows):

for colIndex in range(oldWbS.ncols):

newWs.write(rowIndex + 1, colIndex, oldWbS.cell(rowIndex, colIndex).value)

newWb.save('fileName.xls')

print "save with same name ok"

from xlrd import open_workbook

from xlutils.copy import copy

#在创建好的excel种追加新的数据

if __name__ == '__main__':

 腊祥枣   r_xls = open_workbook("excelTest.xls")  # 读取excel文件

    row = r_xls.sheets()[0].nrows  # 获取已有的行数

    excel = copy(r_xls)  # 将xlrd的对象转化为xlwt的对象

    worksheet = excel.get_sheet(0)  # 获取要 *** 作的sheet

    # 对excel表追加一行内容

    worksheet.write(row, 0, '内容1')  # 括号内分别为行数、列数、内容

    worksheet.write(row, 1, '内容2')

    worksheet.write(row, 2, '内容宴粗3')

    excel.save("excelTest.xls")  # 保存并覆盖文件

结果:轮拆 内容虽然添加进去了,但是原来的excel格式被清除了

原Excel:

追加后的excel:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11981104.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存