用pywin32使excel单元格居左
时间: 2023-06-25 15:07:55 浏览: 99
可以使用 pywin32 中的 `win32com` 模块来操作 Excel,具体步骤如下:
1. 导入 `win32com` 模块:
```python
import win32com.client as win32
```
2. 打开 Excel 文件:
```python
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(r'C:\path\to\your\file.xlsx')
worksheet = workbook.Worksheets('Sheet1')
```
3. 设置单元格格式:
```python
# 获取单元格对象
cell = worksheet.Cells(1, 1)
# 设置单元格内文本居左
cell.HorizontalAlignment = win32.constants.xlLeft
```
4. 保存并关闭 Excel 文件:
```python
workbook.Save()
workbook.Close()
excel.Quit()
```
完整代码示例:
```python
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
workbook = excel.Workbooks.Open(r'C:\path\to\your\file.xlsx')
worksheet = workbook.Worksheets('Sheet1')
cell = worksheet.Cells(1, 1)
cell.HorizontalAlignment = win32.constants.xlLeft
workbook.Save()
workbook.Close()
excel.Quit()
```
阅读全文