python处理excel数据处理
时间: 2023-11-05 20:56:39 浏览: 54
Python可以使用一些库来处理Excel数据,例如xlrd、xlwt和pandas等。其中,xlrd用于读取Excel文件的数据,xlwt用于创建新的Excel并进行写入操作,而pandas是一个功能强大的数据分析库,可以处理各种数据,包括Excel数据。
例如,你可以使用xlrd来读取Excel文件的数据,并将其保存到字典中:
```python
import xlrd
def load_data(file_list):
dictory = {}
for file in file_list:
book = xlrd.open_workbook(file)
sheet = book.sheet_by_index(0)
rows = sheet.nrows
cols = sheet.ncols
head = sheet.row_values(0)
for row in range(rows-1):
if not sheet.cell_value(row+1, 0) in dictory.keys():
dictory[sheet.cell_value(row+1, 0)] = {}
for col in range(cols-1):
dictory[sheet.cell_value(row+1, 0)][head[col+1]] = float(sheet.cell_value(row+1, col+1))
return dictory
```
然后,你可以使用xlwt来保存合并后的数据并生成新的Excel文件:
```python
import xlwt
def save(dictory):
name = input("请输入文件名(无需加后缀):")
book = xlwt.Workbook()
sheet = book.add_sheet('Sheet1', cell_overwrite_ok=True)
keys = list(dictory[list(dictory.keys())[0]].keys())
head = ["城市"]
head.extend(keys)
for h in range(len(head)):
sheet.write(0, h, head[h])
cities = list(dictory.keys())
for city in range(len(cities)):
sheet.write(city+1, 0, cities[city])
for key in range(len(keys)):
sheet.write(city+1, key+1, dictory[cities[city]][keys[key]])
book.save(name+'.xls')
print("保存成功")
```
这样,你就可以方便地处理和操作Excel数据了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)