Python —— excel文件操作(超详细)
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                
import pandas as pd
 
# 读取Excel文件
def read_excel(file_path):
    df = pd.read_excel(file_path)
    print(df)
 
# 写入Excel文件
def write_excel(file_path, data):
    with pd.ExcelWriter(file_path) as writer:
        data.to_excel(writer, index=False, header=True)
 
# 更新Excel文件
def update_excel(file_path, data, sheet_name='Sheet1'):
    # 读取现有数据
    df = pd.read_excel(file_path, sheet_name=sheet_name)
    # 合并数据
    df = pd.concat([df, data], ignore_index=True)
    # 写入新数据
    df.to_excel(file_path, index=False, header=True)
 
# 示例数据
data_to_write = pd.DataFrame({
    'Column1': ['Value1', 'Value2', 'Value3'],
    'Column2': ['Value4', 'Value5', 'Value6']
})
 
# 示例文件路径
file_path = 'example.xlsx'
 
# 读取Excel文件
read_excel(file_path)
 
# 写入Excel文件
write_excel(file_path, data_to_write)
 
# 更新Excel文件
update_excel(file_path, data_to_write)这段代码展示了如何使用Python和pandas库来进行Excel文件的基本操作,包括读取、写入和更新。这对于需要在Python中处理Excel数据的开发者来说是一个实用的教程。
评论已关闭