python xlwt,xlutils 在excel里面如何插入一行数据

一般可以通过write写入数据,但是怎么插入一行呢?
2025-03-06 15:17:46
推荐回答(2个)
回答1:

确实还真就没用过这样的函数,不过可以自己实现。

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

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";

回答2:

没用过,给你个思路:
1、看看能不能定位为到要插入的那行,然后进行写操作,看看是不是原先的下一行被挤下去了
2、如果不行看看这个模块的文档