import random
import xlsxwriter
workbook = xlsxwriter.Workbook('data.xlsx')
sheet = workbook.add_worksheet()
for i in range(10):
ret = random.uniform(100, 150)
ret = (round(ret, 3))
# 把生成的数据全部导入表格
sheet.write(i, 0, ret)
print(ret)
workbook.close()
先安装模块xlsxwriter:pip install xlsxwriter。
插入多行数据重点在于write方法的参数传入。通过按Ctrl+点击方法名write(鼠标左键)查看write方法的详细信息。
@convert_cell_args
def write(self, row, col, *args):
"""
Write data to a worksheet cell by calling the appropriate write_*()
method based on the type of data being passed.
Args:
row: The cell row (zero indexed).
col: The cell column (zero indexed).
*args: Args to pass to sub functions.
Returns:
0: Success.
-1: Row or column is out of worksheet bounds.
other: Return value of called method.
"""
return self._write(row, col, *args)
可以看出row、col分别表示行与列,想要写入第一列的不同行,因为表格索引从0开始,所以给row、col分别传值i、0。