一、讀取Excel文件
在進行批量修改前,首先需要讀取Excel文件中的內容。可以使用Python中的pandas庫快讀取Excel文件。示例如下:
import pandas as pd
df = pd.read_excel('data.xlsx', header=0)
print(df.head())
其中,’data.xlsx’是Excel文件名,header=0表示取第一行為列名。讀取完成後,可以使用df.head()來查看錶格前5行。
二、修改單元格內容
修改單元格內容需要使用pandas庫來進行操作。可以根據表格的行列位置修改單元格內容:
import pandas as pd
df = pd.read_excel('data.xlsx', header=0)
df.iloc[0, 0] = 'new_content'
print(df.head())
其中,iloc[0, 0]表示第一行第一列單元格,修改為’new_content’。
三、批量修改單元格內容
如果需要批量修改單元格內容,則可以使用循環遍歷表格,並對符合條件的單元格進行修改。示例如下:
import pandas as pd
df = pd.read_excel('data.xlsx', header=0)
for i in range(len(df)):
if df.iloc[i, 0] == 'condition':
df.iloc[i, 1] = 'new_content'
print(df.head())
其中,if語句判斷第一列是否符合條件,若符合則將第二列修改為’new_content’。
四、添加新的單元格內容
如果需要向Excel表格中添加新的單元格內容,則可以使用pandas庫的append方法。示例如下:
import pandas as pd
df = pd.read_excel('data.xlsx', header=0)
new_data = {'column1': 'new_content1', 'column2': 'new_content2'}
df = df.append(new_data, ignore_index=True)
print(df.tail())
其中,new_data為一個字典,表示新添加的數據。ignore_index=True是為了保證添加的數據在最後一行。
五、保存修改後的Excel文件
修改完成後,需要將修改後的Excel文件保存。可以使用pandas庫的to_excel方法來實現。示例如下:
import pandas as pd
df = pd.read_excel('data.xlsx', header=0)
for i in range(len(df)):
if df.iloc[i, 0] == 'condition':
df.iloc[i, 1] = 'new_content'
df.to_excel('new_data.xlsx', index=False)
print('Save Excel file successfully!')
其中,’new_data.xlsx’為保存的Excel文件名,index=False表示不保存原有Excel文件的索引值。
原創文章,作者:EXCFY,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/370396.html