如何用Python替换多个excel表中的[cell]内容?

2024-10-08 18:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Excel表格,包含不同的单位值,比如“一百”和“千”。在

现在,我想把所有的“千”改为“一百”,这意味着原始单元格值将[cell]乘以10。在

我用VBA解决了这个问题,我想知道如何用python来解决这个问题?在

VBA like this :

Sub changecell()
Dim rng As Range
Dim i, t
Set rng = Sheet1.Range("b3:c5")
For Each i In rng
    t = t + 1
    If Not i Is Nothing Then
        If Right(i, 4) = "sand" Then
        rng(t) = Left(i, Len(i) - 8) * 10 & "hundred"
        End If
    End If
Next
End Sub

如何使用python从多个excel表中替换这些[单元格]? enter image description here


Tags: if单位cellrangevbathisexcellike
2条回答

将excel工作表另存为csv文件,然后尝试以下操作:

import csv 


with open('path_name_to_new_file', 'w', newline='') as newfile:
    with open('path_name_to_original_file', newline='') as original:
        writer = csv.writer(newfile, delimiter=',')
        reader = csv.reader(original, delimiter=',')
        for row in reader: 
            row[1] = row[1] * 10
            row[2] = row[2] * 10
            writer.writerow(row)

编辑:

所以,你有成百上千的excel文件。。。不是所有的专栏。未测试代码:

^{pr2}$

如果你需要用Python来做,使用pandas

但此VBA将在当前工作簿的所有工作表中执行替换:


Option Explicit

Public Sub GlobalReplaceThousandToHundred()
    Dim ws As Worksheet, ur As Variant, r As Long, c As Long, sz As Long

    Const STR1 = "thousand"
    Const STR2 = "hundred"

    sz = Len(STR1)

    For Each ws In ThisWorkbook.Worksheets
        ur = ws.UsedRange
        For r = LBound(ur) To UBound(ur)
            For c = LBound(ur, 2) To UBound(ur, 2)
                If Not IsError(ur(r, c)) Then
                    If LCase(Right(ur(r, c), sz)) = STR1 Then
                        ur(r, c) = Left(ur(r, c), Len(ur(r, c)) - sz) & STR2
                    End If
                End If
            Next
        Next
        ws.UsedRange = ur
    Next
End Sub

相关问题 更多 >

    热门问题