Python生成Excel文件的三种方法

  1. 类库xlwt/xlrd
  1. 类库openpyxl
  1. 类库pandas
0、读取txt文件
columns = []
datas = []
with open("./pvuv.txt") as fin:
    is_first_line = True
    for line in fin:
        line = line[:-1]
        if is_first_line:
            is_first_line = False
            columns = line.split("\t")
            continue
        
        datas.append(line.split("\t"))
1、使用xlwt生成xls的excel文件
# pip install xlwt
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
sheet = workbook.add_sheet('pvuv_sheet')

# 写入标题
for col,column in enumerate(columns):
    sheet.write(0, col, column)
# 写入每一行
for row, data in enumerate(datas):
    for col, column_data in enumerate(data):
        sheet.write(row+1, col, column_data)

workbook.save('./output/pvuv_xlwt.xls')
2、使用openpyxl生成xlsx的excel文件
# pip install openpyxl
from openpyxl import Workbook
workbook = Workbook()

# 默认sheet
sheet = workbook.active
sheet.title = "默认sheet"
# sheet = workbook.create_sheet(title="新sheet")
sheet.append(columns)
for data in datas:
    sheet.append(data)

workbook.save('./output/pvuv_openpyxl.xlsx')
3、使用pandas生成excel文件
# pip install pandas
import pandas as pd
# 读取文本文件
data = pd.read_csv("./pvuv.txt", sep="\t")
data.to_excel("./output/pvuv_pandas.xls", index=False)
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐