python CSV 多组数据存到excel
时间: 2024-09-08 18:00:48 浏览: 51
在Python中,将多组CSV数据存储到Excel文件中可以通过使用`pandas`库来实现,因为`pandas`提供了强大的数据处理能力,包括读取CSV文件和将数据写入Excel文件的功能。以下是完成这个任务的基本步骤:
1. 使用`pandas`的`read_csv`函数读取多个CSV文件。
2. 将每个CSV文件的数据存储到`pandas`的DataFrame对象中。
3. 使用`pandas`的`ExcelWriter`和`to_excel`方法将DataFrame对象写入到Excel文件中。
4. 可以指定不同的工作表名来区分不同的CSV数据。
下面是一个简单的代码示例:
```python
import pandas as pd
# 假设我们有两个CSV文件:file1.csv 和 file2.csv
file_list = ['file1.csv', 'file2.csv']
# 创建一个Excel文件写入器
with pd.ExcelWriter('output.xlsx') as writer:
# 遍历所有CSV文件
for file in file_list:
# 读取CSV文件到DataFrame
df = pd.read_csv(file)
# 将DataFrame写入到Excel的不同工作表中
# sheet_name参数用于指定工作表的名称
df.to_excel(writer, sheet_name=file.replace('.csv', ''))
# 这样,每个CSV文件的数据就会被存储到output.xlsx中的不同工作表中。
```
确保在运行这段代码之前已经安装了`pandas`库和`openpyxl`库(后者用于写入`.xlsx`文件)。
阅读全文
相关推荐


















