python openpyxl 写入数值格式的数字
时间: 2023-08-05 19:39:42 浏览: 212
你可以使用openpyxl库中的NumberFormat类来写入数值格式的数字。具体方法如下:
1. 导入openpyxl库:
```python
import openpyxl
```
2. 打开Excel文件:
```python
workbook = openpyxl.load_workbook('example.xlsx')
```
3. 选择要写入的工作表:
```python
worksheet = workbook['Sheet1']
```
4. 写入数值格式的数字:
```python
from openpyxl.styles import numbers
cell = worksheet.cell(row=1, column=1)
cell.value = 1234.56
cell.number_format = numbers.FORMAT_NUMBER_COMMA_SEPARATED1
```
在上面的示例中,我们使用了`numbers.FORMAT_NUMBER_COMMA_SEPARATED1`来设置数值格式为带有千位分隔符的数字。
5. 保存Excel文件:
```python
workbook.save('example.xlsx')
```
这样就可以写入数值格式的数字了。
相关问题
python openpyxl写入数据
要使用 openpyxl 库在 Excel 中写入数据,首先需要安装 openpyxl 库。然后可以使用以下代码打开一个工作簿并写入数据:
```python
import openpyxl
# 打开工作簿
wb = openpyxl.Workbook()
# 选择活动工作表
ws = wb.active
# 在 A1 单元格写入数据
ws['A1'] = 'hello'
# 保存工作簿
wb.save('example.xlsx')
```
这段代码将在当前目录中创建一个名为 example.xlsx 的新 Excel 文件,并在第一个工作表的 A1 单元格中写入 "hello"。
python openpyxl写入列表数据
在Python中,使用openpyxl库可以方便地操作Excel文件,包括写入数据。如果你有一个包含列表的数据,想要写入到Excel的工作表中,你可以按照以下步骤操作:
首先,你需要安装`openpyxl`库,如果还没有安装,可以在命令行运行`pip install openpyxl`。
```python
import openpyxl
# 假设你有一个二维列表 data
data = [
['姓名', '年龄'],
['张三', '25'],
['李四', '30']
]
# 加载或创建一个新的Excel工作簿
workbook = openpyxl.Workbook()
sheet = workbook.active # 默认的第一个工作表
# 写入数据
for i, row in enumerate(data):
sheet.cell(row=i+1, column=1, value=row[0]) # 第一列写入字符串
sheet.cell(row=i+1, column=2, value=row[1]) # 第二列写入整数或其他类型
# 保存Excel文件
workbook.save('example.xlsx')
```
在这个例子中,我们遍历列表中的每一项,然后分别将它们写入到对应的位置。`row=i+1`是因为索引从0开始,我们需要加1才能对应到实际行号。
阅读全文
相关推荐
















