worksheet = workbook.Worksheets.Add() worksheet.Name = "货机数据" cell_range = worksheet.Range("A1:G" + str(len(air_data) + 1)) # 包含列标题的单元格范围 cell_range.Value = air_data.values # 将数据写入单元格范围 # 设置单元格居中 cell_range.HorizontalAlignment = win32.constants.xlCenter # 设置日期格式为yyyy-mm date_format = "yyyy-mm" worksheet.Range("A2:A" + str(len(air_data) + 1)).NumberFormat = date_format # 保存并关闭Excel表格 workbook.Save() workbook.Close() excel.Quit()如何在这里添加一段代码 使win32读取的数据包含列标题
时间: 2024-03-27 11:35:55 浏览: 64
在`cell_range.Value = air_data.values`这一行代码之前,添加以下代码即可:
```python
# 写入列标题
for i, col in enumerate(air_data.columns):
worksheet.Cells(1, i+1).Value = col
```
`air_data.columns`返回的是`pandas`读取的数据的列标题,将其按列写入第一行即可。完整代码如下:
```python
import pandas as pd
import win32com.client as win32
# 读取数据
air_data = pd.read_csv('air_data.csv')
# 创建Excel文件
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Add()
worksheet = workbook.Worksheets.Add()
worksheet.Name = "货机数据"
# 写入列标题
for i, col in enumerate(air_data.columns):
worksheet.Cells(1, i+1).Value = col
# 写入数据
cell_range = worksheet.Range("A2:G" + str(len(air_data) + 1))
cell_range.Value = air_data.values
# 设置单元格居中
cell_range.HorizontalAlignment = win32.constants.xlCenter
# 设置日期格式为yyyy-mm
date_format = "yyyy-mm"
worksheet.Range("A2:A" + str(len(air_data) + 1)).NumberFormat = date_format
# 保存并关闭Excel表格
workbook.SaveAs('air_data.xlsx')
workbook.Close()
excel.Quit()
```
阅读全文