帮我编写一段代码,实现利用相关库,用Python实现CSV、Excel、Word文件的创建和读写操作
时间: 2024-04-29 22:25:17 浏览: 126
基于python实现自动化办公学习笔记(CSV、word、Excel、PPT)
好的,我很乐意帮您编写这段代码,请稍等。
下面是Python代码实现CSV、Excel、Word文件的创建和读写操作:
```
import csv
import openpyxl
from docx import Document
# 创建CSV文件
with open('test.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age', 'Gender'])
writer.writerow(['Tom', '25', 'Male'])
writer.writerow(['Lucy', '22', 'Female'])
# 读取CSV文件
with open('test.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# 创建Excel文件
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = 'Name'
ws['B1'] = 'Age'
ws['C1'] = 'Gender'
ws['A2'] = 'Tom'
ws['B2'] = '25'
ws['C2'] = 'Male'
ws['A3'] = 'Lucy'
ws['B3'] = '22'
ws['C3'] = 'Female'
wb.save('test.xlsx')
# 读取Excel文件
wb = openpyxl.load_workbook('test.xlsx')
ws = wb.active
for row in ws.iter_rows(min_row=1, max_col=3):
for cell in row:
print(cell.value, end=' ')
print()
# 创建Word文件
doc = Document()
doc.add_heading('Personal Information', 0)
table = doc.add_table(rows=3, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Age'
hdr_cells[2].text = 'Gender'
row1_cells = table.rows[1].cells
row1_cells[0].text = 'Tom'
row1_cells[1].text = '25'
row1_cells[2].text = 'Male'
row2_cells = table.rows[2].cells
row2_cells[0].text = 'Lucy'
row2_cells[1].text = '22'
row2_cells[2].text = 'Female'
doc.save('test.docx')
# 读取Word文件
doc = Document('test.docx')
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text.strip(), end=' ')
print()
```
以上就是实现CSV、Excel、Word文件的创建和读写操作的Python代码。希望对您有所帮助!
阅读全文