用Python实现Excel文件的创建和读写操作
时间: 2024-05-14 14:12:28 浏览: 20
创建Excel文件:
```python
import openpyxl
#创建工作簿
wb = openpyxl.Workbook()
#创建工作表
sheet = wb.active
#设置单元格的值
sheet['A1'] = '姓名'
sheet['B1'] = '性别'
sheet['C1'] = '年龄'
sheet['A2'] = '张三'
sheet['B2'] = '男'
sheet['C2'] = 25
sheet['A3'] = '李四'
sheet['B3'] = '女'
sheet['C3'] = 28
#保存工作簿
wb.save('test.xlsx')
```
读取Excel文件:
```python
import openpyxl
#打开工作簿
wb = openpyxl.load_workbook('test.xlsx')
#选择工作表
sheet = wb.active
#获取单元格的值
name = sheet['A2'].value
sex = sheet['B2'].value
age = sheet['C2'].value
print('姓名:', name)
print('性别:', sex)
print('年龄:', age)
```
相关问题
利用相关库,用Python实现CSV、Excel、Word文件的创建和读写操作
可以使用Python自带的csv、xlrd、xlwt、openpyxl、docx等库实现CSV、Excel、Word文件的创建和读写操作。例如,使用csv库可以通过以下代码将数据写入CSV文件中:
```python
import csv
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.csv'
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
```
使用xlwt库可以通过以下代码将数据写入Excel文件中:
```python
import xlwt
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.xls'
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('Sheet1')
for i, row in enumerate(data):
for j, col in enumerate(row):
worksheet.write(i, j, col)
workbook.save(filename)
```
使用openpyxl库可以通过以下代码将数据写入Excel文件中:
```python
import openpyxl
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.xlsx'
workbook = openpyxl.Workbook()
worksheet = workbook.active
for row in data:
worksheet.append(row)
workbook.save(filename)
```
使用docx库可以通过以下代码将数据写入Word文件中:
```python
import docx
data = [['name', 'age', 'gender'], ['Tom', 18, 'male'], ['Lily', 20, 'female']]
filename = 'data.docx'
document = docx.Document()
for row in data:
table = document.add_table(rows=1, cols=len(row))
hdr_cells = table.rows[0].cells
for i, col in enumerate(row):
hdr_cells[i].text = col
document.save(filename)
```
pythonexcel文件读写操作类封装
以下是一个简单的 Python Excel 文件读写操作的类封装示例:
```python
import pandas as pd
class ExcelFile:
def __init__(self, file_path):
self.file_path = file_path
self.data = None
# 读取 Excel 文件
def read_file(self):
try:
# 使用 pandas 库读取 Excel 文件
self.data = pd.read_excel(self.file_path)
except FileNotFoundError:
print(f"File {self.file_path} not found.")
# 写入 Excel 文件
def write_file(self):
try:
# 将数据写入到 Excel 文件中
writer = pd.ExcelWriter(self.file_path)
self.data.to_excel(writer, index=False)
writer.save()
print(f"File {self.file_path} saved successfully.")
except:
print(f"Failed to save file {self.file_path}.")
# 测试代码
if __name__ == "__main__":
# 创建 ExcelFile 对象
excel_file = ExcelFile("example.xlsx")
# 读取 Excel 文件
excel_file.read_file()
if excel_file.data is not None:
print(excel_file.data)
# 写入 Excel 文件
new_data = {"Name": ["John", "Mary", "Peter"], "Age": [30, 25, 40]}
df = pd.DataFrame(new_data)
excel_file.data = df
excel_file.write_file()
```
在这个示例中,我们定义了一个名为 `ExcelFile` 的类,这个类封装了 Excel 文件的读取和写入操作。在初始化函数中,我们传入一个文件路径,并将其保存为类的属性。`read_file` 函数尝试读取这个文件,并将读取到的数据保存为类的属性。`write_file` 函数将类的属性中的数据写入到对应的文件中。
在测试代码中,我们首先创建一个 `ExcelFile` 对象,并调用 `read_file` 函数来读取一个名为 `example.xlsx` 的 Excel 文件,并将读取到的数据输出到控制台。然后我们创建一个新的 DataFrame 对象,并将其保存为 `ExcelFile` 对象的属性,最后调用 `write_file` 函数将这个 DataFrame 中的数据写入到一个名为 `example.xlsx` 的 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_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)
![](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)