Python Xlsxwriter 简明教程

Python XlsxWriter - Hello World

Getting Started

第一个测试模块/库正常运行的程序通常是写 Hello world 消息。下列程序创建一个带 .XLSX 扩展名的文件。xlsxwriter 模块中 Workbook 类的对象对应于当前工作目录中的电子表格文件。

The first program to test if the module/library works correctly is often to write Hello world message. The following program creates a file with .XLSX extension. An object of the Workbook class in the xlsxwriter module corresponds to the spreadsheet file in the current working directory.

wb = xlsxwriter.Workbook('hello.xlsx')

接下来,调用 Workbook 对象的 add_worksheet() 方法在其中插入一个新工作表。

Next, call the add_worksheet() method of the Workbook object to insert a new worksheet in it.

ws = wb.add_worksheet()

我们现在可以通过调用工作表对象的 write() 方法在 A1 单元格中添加 Hello World 字符串。它需要两个参数:单元格地址和字符串。

We can now add the Hello World string at A1 cell by invoking the write() method of the worksheet object. It needs two parameters: the cell address and the string.

ws.write('A1', 'Hello world')

Example

hello.py 的完整代码如下 −

The complete code of hello.py is as follows −

import xlsxwriter
wb = xlsxwriter.Workbook('hello.xlsx')
ws = wb.add_worksheet()
ws.write('A1', 'Hello world')
wb.close()

Output

在执行上述代码后,将在当前工作目录中创建 hello.xlsx 文件。你现在可以使用 Excel 软件打开它。

After the above code is executed, hello.xlsx file will be created in the current working directory. You can now open it using Excel software.

hello world