使用win32com和python擦除excel的一部分

时间:2013-03-08 14:02:32

标签: python excel python-2.7 win32com

我有3个参数。

startLine,starColumn和width(此处为2,8,3)

excel

如何在不在每个单元格中写入空白的情况下擦除所选区域? (这里只有30行,但可能有10 000行)

现在我已成功计算行数,但我无法找到如何选择和删除某个区域

self.startLine = 2
self.startColumn = 8
self.width = 8

self.xl = client.Dispatch("Excel.Application")
self.xl.Visible = 1
self.xl.ScreenUpdating = False
self.worksheet = self.xl.Workbooks.Open("c:\test.xls")
sheet = self.xl.Sheets("data")

#Count the number of line of the record
nb = 0
while sheet.Cells(start_line + nb, self.startColumn).Value is not None:
    nb += 1

#must select from StartLine,startColumn to startcolum+width,nb
#and then erase

self.worksheet.Save()

ps:代码有效,我可能已经忘记了部分因为复制/失败错误,实际上excel文件的处理是由几个继承的类管理的

感谢

3 个答案:

答案 0 :(得分:1)

我通常做的是在Excel中记录宏,而不是尝试在Python中重新破解VB。对于删除内容,我得到类似的东西,不应该很难将其转换为Python:

Range("H5:J26").Select
Selection.ClearContents

在Python中应该是这样的:

self.xl.Range("H5:J26").Select()
self.xl.Selection.ClearContents()

工作示例:

from win32com.client.gencache import EnsureDispatch

exc = EnsureDispatch("Excel.Application")
exc.Visible = 1
exc.Workbooks.Open(r"f:\Python\Examples\test.xls")
exc.Sheets("data").Select()
exc.Range("H5:J26").Select()
exc.Selection.ClearContents()

答案 1 :(得分:0)

这对我有用

xl = EnsureDispatch('Excel.Application') 
wb2=xl.Workbooks.Open(file)
ws=wb2.Worksheets("data")

ws.Range("A12:B20").ClearContents()

答案 2 :(得分:-1)

 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
        res = super(res_users, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        if view_type == 'form':
            model_obj = self.pool.get('ir.model.data')
            tmp, target_view_id = model_obj.get_object_reference(cr, uid, 'base','view_users_form_simple_modif')
            doc = etree.XML(res['arch'])
            if view_id and view_id == target_view_id:
                nodes = doc.xpath("//field[@name='context_warehouse']")
                tmp, group_id = model_obj.get_object_reference(cr, uid, 'monos_base','group_can_change_context_warehouse')
                cr.execute("select count(*) from res_groups_users_rel where uid = %s and gid = %s",(uid, group_id,))
                fetched = cr.fetchone()[0]
                if fetched > 0:
                    for node in nodes:
                        node.set('readonly', '0')
                        node.set('modifiers', '{"required": true}')
                else :
                    for node in nodes:
                        node.set('readonly', '1')
                        node.set('modifiers', '{"required": false,"readonly": true}')
            nodes = doc.xpath("//field[@name='context_tz']")
            for node in nodes:
                node.set('readonly', '1')
            res['arch'] = etree.tostring(doc)
        return res