1. Install xlwt library
Terminal input
pip install xlwt
If you are using Python 3, you may need to use pip3
the command:
pip3 install xlwt
2. Import xlwt library
import xlwt
3. Create a new Excel workbook and worksheet:
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
4. Write the contents of the string array to the Excel worksheet line by line:
str_array = ["第一行内容", "第二行内容", "第三行内容"]
for i in range(len(str_array)):
ws.write(i, 0, str_array[i])
In the above code, ws.write(i, 0, str_array[i])
it means the content written in i
row 0 and column 0 (that is, the first column) str_array[i]
.
5. Save the Excel file:
wb.save('output.xls')
In the above code, wb.save('output.xls')
the Excel file will be saved as "output.xls".
The complete code is as follows:
import xlwt
# 创建一个新的Excel工作簿和工作表
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
# 创建一个字符串数组
str_array = ["第一行内容", "第二行内容", "第三行内容"]
# 将字符串数组的内容逐行写入Excel工作表
for i in range(len(str_array)):
ws.write(i, 0, str_array[i])
# 保存Excel文件
wb.save('output.xls')