Reading and Writing Excel Data in Python 3

Asked 2 years ago, Updated 2 years ago, 92 views

I'm a beginner at python and I don't understand the basics very well, but please let me know.

I'm trying to read and write Excel data on python3 because I feel the limitation of Excel VBA.
xlrd, xlwt. I can't do it well.

For example,
in Excel (designated file, designated sheet) Read the values (reads) in column A from the first line and
How do I write a value in column B?

#-*-coding:utf-8-*-

import xlrd
import xlwt

book=xlrd.open_workbook('j.xls') 
sheet_1 = book.sheet_by_index(0)

for row in range (sheet_1.nrows):
    if sheet_1.cell(row,1).value>=10:
        sheet_1.write(row, 2, '10 or higher')
    else
        sheet_1.write(row, 2, 'less than 10')

python3 excel

2022-09-30 21:24

1 Answers

For the time being, if we rewrite it as follows, we will be able to accomplish the tasks requested.

Perhaps the intention of the question is to simply and flexibly overwrite the existing sheet, but I am not familiar with the Excel output from Python, so I cannot add any valid advice.

#-*-coding:utf-8-*-

import xlrd
import xlwt
# Excel loading
reader=xlrd.open_workbook('j.xls') 
r_sheet=reader.sheet_by_index(0)
# Write sheet creation
writer=xlwt.Workbook()
w_sheet=writer.add_sheet(r_sheet.name)#Same name as read sheet to overwrite and save
for row in range(r_sheet.nrows):
    w_sheet.write(row,0,r_sheet.cell(row,0).value)#Copy Existing Value
    ifr_sheet.cell(row,0).value>=10:
        w_sheet.write(row, 1, '10 or higher')
    else:
        w_sheet.write(row, 1, 'less than 10')
writer.save('j.xls')# Overwrite Save


2022-09-30 21:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.