简体   繁体   English

使用xlrd和xlwt修改Excel

[英]Modifying Excel using xlrd and xlwt

I am creating a new excel from an existing excel . 我正在从现有的excel创建一个新的excel。 There ares 3 Sheets in my old excel say first , second , third . 我以前的Excel中有3 Sheets secondfirstsecondthird I am able to copy the contents of first sheet succesfully in new excel which is based on some condition ie my code before while index < 3 : works perfectly fine . 我能够在新的excel中成功复制第一张纸的内容,这是基于某种条件的,即我的代码在while index < 3 :工作得很好。 For sheet second and third I want to copy them as they are in original excel sheet . 对于secondthird张纸,我要复制它们,就像它们在original excel sheet But When the copy starts for second sheet I get an error :- 但是,当second张纸开始复印时,出现错误:-

sheet1 = w.add_sheet('Info')
File "/usr/local/lib/python2.7/site-packages/xlwt/Workbook.py", line 331, in add_sheet
raise Exception("duplicate worksheet name %r" % sheetname) 

My code is as follows:- 我的代码如下:

newexcel = "newexcel.xls"
    count = 0
    wb = xlrd.open_workbook('/home/sam/myexcel.xls')
    w = Workbook()
    sheet = w.add_sheet('Input_Resource')
    index = 0
    s = wb.sheet_by_index(index)
    if index < 1 :
        index =+ 1
        for row in range(s.nrows):
            coln =0
            val = s.cell(row,coln).value
            if val in MissingId :
                mylist.append(val)
                count += 1
            else:
                for col in range(s.ncols):
                    val = s.cell(row,col).value
                    sheet.write(row-count,col,val)
    while index < 3 :
        if index == 1 :
            sheet1 = w.add_sheet('Info')
        else :
            sheet2 = w.add_sheet('Sheet3')

        s = wb.sheet_by_index(index)
        index =+ 1
        for row in range(s.nrows):
            coln =0
            val = s.cell(row,coln).value
            for col in range(s.ncols):
                val = s.cell(row,col).value
                if index == 1:
                    sheet1.write(row,col,val)
                else :
                    sheet2.write(row,col,val)
w.save(newexcel)

Any Help or hint is appreciated :) 任何帮助或提示表示赞赏:)

Below some idea for check duplicate sheets: 下面是一些检查重复表的想法:

import xlwt

wb = xlwt.Workbook()
#Adding 2 sheets
ws1 = wb.add_sheet('One')
ws2 = wb.add_sheet('Two')

sheets = wb._Workbook__worksheets #Getting sheets list
sheet_names = [] #List for shhets names
for sheet in sheets:
     sheet_names.append(
         sheet.get_name() #getting sheet name
         ) 
print sheet_names
print True if u"One" in sheet_names else False #check for our name
wb.save('test.xls')

Results: 结果:

$python simple.py 
[u'One', u'Two']
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM