目录

2 通过 Python 和 XlsxWriter 创建 Excel 文件

优质
小牛编辑
115浏览
2023-12-01

XlsxWriter是一个Python的第三方模块,用来创建Excel的xlsx文件。

##################################
#
# A simple example of some of the features of the XlsxWriter Python module.
#
# Copyright 2013-2020, John McNamara, jmcnamara@cpan.org
#
import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)

# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})

# Write some simple text.
worksheet.write('A1', 'Hello')

# Text with formatting.
worksheet.write('A2', 'World', bold)

# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)

# Insert an image.
worksheet.insert_image('B5', 'logo.png')

workbook.close()

XlsxWriter

XlsxWriter是一个Python第三方模块,可以将文本、数字、公式和超链接写入Excel 2007以上版本的xlsx文件的多个工作簿中。它还支持格式化等功能,其中包括:

  • 100%兼容Excel的xlsx文件;
  • 完整的格式;
  • 合并单元格;
  • 定义名称;
  • 图表;
  • 自动过滤器;
  • 数据验证和下拉列表;
  • 条件格式;
  • 工作簿的PNG、JPEG、BMP、WMF、EMF等图像;
  • 丰富的多格式字符串;
  • 单元格注释;
  • 文本框;
  • 与Pandas模块整合;
  • 用于写入大文件的内存优化模式;

它支持Python2.7、3.4+和Pypy,并且仅使用Python的标准库,不依赖任何第三方库。