简体   繁体   中英

How to replace [cell] content from multi excel sheets with Python?

I have an Excel sheet,contains different units value ,like "hundred" and "thousand".

Now,I want change all "thousand" to "hundred",it means orginal cell value will [cell] times 10.

I use VBA solved this problem,I want to know how to use python to solve this problem?

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

How to use python to replace these [cells] from multi excel sheets? 在此处输入图片说明

Save you excel sheet as csv file, then try this:

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)

EDIT:

So, you have hundreds of excel files... and not all columns. Non tested code:

import pandas

 def test(cell):
    t = str(cell).split(' ')
    t = t[1] if len(t[1]) = 2 else None
    if t == 'thousand':
       return float(cell)*10
    else:
       return cell

excel_file_names = [##make a list of your file names##]
for file in excel_file_names:
    df = pandas.read_excel(file)
    for index,row in df.iterrows():
        row['2016'] = test(row['2016'])
        row['2015'] = test(row['2015'])

    writer = pd.ExcelWriter()
    df.to_excel(writer,'Sheet1')
    writer.save(file + '_modified')

If you need to do it in Python use pandas

but this VBA will perform the replacements in all sheets of the current WorkBook:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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