【问题标题】:How To Write To Excel In Python如何在 Python 中写入 Excel
【发布时间】:2019-08-04 21:16:54
【问题描述】:

我正在尝试编写一个小型“交互式”电子表格程序,以 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")

【问题讨论】:

标签: python excel python-3.x file io


【解决方案1】:

是的,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")

【讨论】:

  • 很抱歉打扰您,但是如何在没有手动编码的情况下向第一列写入公牛号?我只找到了 insert_cols 但它只给出了空格。谢谢!
猜你喜欢
  • 2016-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 2020-12-17
  • 2022-10-13
  • 1970-01-01
  • 2011-09-05
相关资源
最近更新 更多