Ismail Ahmed
Ismail Ahmed

Reputation: 41

How To Write To Excel In Python

I was trying to write a small "interactive" spreadsheet program to export in CSV, TSV, and Excel formats. I succeeded in the first 2, but the last one is where I am having some difficulty. Here is the code:

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")

Upvotes: 1

Views: 8491

Answers (1)

ASH
ASH

Reputation: 20362

Yeah, CSV and TSV files are very easy to work with, especially compared to Excel, where you have all kinds of objects, formatting, etc. Try to adapt the simple scripts below to write to an Excel file.

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")

Upvotes: 3

Related Questions