Python Excel
发表于更新于
字数总计:10k 鞍山
PythonPython Excel
魔力刘易斯安装 Python 库
pip install openpyxl pandas
代码实现示例
创建 Excel 文件
import pandas as pd
df = pd.DataFrame(
{"ID": [1, 2, 3], "name": ["张三", "李四", "王五"], "age": [20, 21, 22]}
)
print(df)
df = df.set_index("ID")
print(df)
df.to_excel("test.xlsx")
print("Excel 文件已创建成功!")
读取 Excel 文件
import pandas as pd
df = pd.read_excel("test.xlsx", engine="openpyxl")
print(df)
print(f"类型为:{type(df)}")
print(df.shape)
print(df.columns)
print(df.head())
修改 Excel 文件
import pandas as pd
df = pd.read_excel("test.xlsx")
print(df)
df.drop(1, inplace=True)
print(df)
df.to_excel("test.xlsx", index=False)
df = pd.read_excel("test.xlsx")
print(df)
df.drop([1, 2], inplace=True)
print(df)
df.to_excel("test.xlsx", index=False)
data = [1, 3, 5, 7, 9]
df = pd.read_excel("test.xlsx")
print(df)
for i in reversed(data):
df.drop(i, inplace=True)
print(df)