gpt4 book ai didi

python - 如何在 Python 中写入 Excel

转载 作者:行者123 更新时间:2023-12-04 21:50:31 26 4
gpt4 key购买 nike

我试图编写一个小的“交互式”电子表格程序,以 CSV、TSV 和 Excel 格式导出。我在前 2 个中成功了,但在最后一个中我遇到了一些困难。这是代码:

import csv
import matplotlib.pyplot as plt
import xlwt

A1 = int(input("Please input the nueercical value for A1. "))
A2 = int(input("Please do the same for A2. "))
prefixnumber = 1, 2, 3, 4
meta = input("please sum this: Press y for yes and n for no.")
wb = xlwt.Workbook()
sh = wb.add_sheet("sheet")

if meta == "y":
field = ['A1', 'A2', 'Meta']
sum = A1 + A2
sumint = int(sum)
print(sum)
rows = [A1, A2, sumint]
with open('yeetboi.csv', 'w') as export:
csvwrite = csv.writer(export, sum)
csvwrite.writerow(field)
csvwrite.writerow(rows)
csvwrite.writerow(prefixnumber)
with open('yeetboi.tsv', 'w') as exporttsv:
tsvwrite = csv.writer(exporttsv, delimiter='\t')
tsvwrite.writerow(field)
tsvwrite.writerow(rows)
tsvwrite.writerow(prefixnumber)
sh.write(0,0,field)

else:
pass
print("nope")

最佳答案

是的,CSV 和 TSV 文件非常易于使用,尤其是与 Excel 相比,Excel 具有各种对象、格式等。尝试调整下面的简单脚本以写入 Excel 文件。

import xlsxwriter


# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('C:/your_path/test.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)


workbook.close()


***********************************************************************************


from openpyxl import Workbook
wb = Workbook()

# grab the active worksheet
ws = wb.active

# Data can be assigned directly to cells
ws['A1'] = 42

# Rows can also be appended
ws.append([1, 2, 3])

# Python types will automatically be converted
import datetime
ws['A2'] = datetime.datetime.now()

# Save the file
wb.save("C:\your_path\\sample.xlsx")

关于python - 如何在 Python 中写入 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55154707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com