获取 excel 表格 shert 指定多列内容.写入另一个已有内容的 excel 表格 shert 指定 多列末行 的 python 代码
时间: 2023-06-18 22:05:38 浏览: 75
你可以使用 `pandas` 库来读写 Excel 文件,并使用 `iloc` 属性来选择指定的列和行。
以下是一个示例代码,假设你要将第一张 Excel 表格中的第一列和第二列的内容写入第二张 Excel 表格中的第一列和第二列的末行:
```python
import pandas as pd
# 读取第一张 Excel 表格中的指定列
df1 = pd.read_excel('file1.xlsx', sheet_name='Sheet1', usecols=[0, 1])
# 读取第二张 Excel 表格中的指定列
df2 = pd.read_excel('file2.xlsx', sheet_name='Sheet1', usecols=[0, 1])
# 获取第二张表格中指定列的末行
last_row = df2.iloc[-1]
# 将第一张表格中的内容写入第二张表格中指定列的末行
df2.loc[len(df2)] = [df1.iloc[0][0], df1.iloc[0][1]]
# 将修改后的第二张表格写入文件
with pd.ExcelWriter('file2.xlsx', mode='a') as writer:
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=len(df2)-1, header=False)
```
在上面的代码中,我们首先使用 `pd.read_excel()` 函数读取第一张和第二张 Excel 表格中指定的列,然后使用 `iloc` 属性获取第二张表格中指定列的末行。接着,我们使用 `df2.loc[len(df2)]` 语句将第一张表格中的内容写入第二张表格中指定列的末行,并使用 `pd.ExcelWriter()` 函数将修改后的第二张表格写入文件。请注意,在写入时,我们使用 `startrow=len(df2)-1` 参数指定从第二张表格中指定列的末行开始写入数据。