[英]How to replace [cell] content from multi excel sheets with Python?
我有一张Excel工作表,包含不同的单位值,例如“一百”和“千”。
现在,我要将所有的“千”更改为“百”,这意味着原始单元格值将是[单元格]的10倍。
我用VBA解决了这个问题,我想知道如何用python解决这个问题吗?
VBA是这样的:
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
将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文件...而不是所有列。 未经测试的代码:
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')
如果您需要在Python中使用熊猫
但是此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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.