Home > Back-end >  Python! Read Value of Columns in Excel
Python! Read Value of Columns in Excel

Time:07-18

I want to insert values from Python into an Excel sheet. I can't figure out the way to go about this. I would like to make a for-loop to determine the last entry in column[0] (vertically) in my Excel sheet. This is my python code:

# Modules
import datetime, os, sys, json, requests, time, openpyxl, xlrd, xlwt
from itertools import count
import urllib.request as request
from urllib.parse import urlparse, parse_qs
from openpyxl import Workbook
from openpyxl import load_workbook
from xlwt import Workbook
from cgitb import text
from re import X
from flask import Flask, request, render_template
from datetime import datetime, time, date

#Flask Constructor
app = Flask(__name__)

#Main Function
@app.route('/')
def main():
    return render_template('index.html')

#Excel Convert Function
@app.route('/initiate_excel_corvert',  methods=['GET', 'POST'])
def initiate_excel_corvert():
    
    #Get URL
    id = request.args.get('ID')

    #Sort Values From URL
    a = id.split('_*_')[0]
    b = id.split('_*_')[1]
    c = id.split('_*_')[2]
    d = id.split('_*_')[3]

    #Counter
    counter1 = 1
    A_counter = 0

    #Excel Variables
    dest_filename = 'empty_book.xlsx'
    dest_filename_sheet = 'Sheet 1'

    #Openpyxl Workbook
    wb = Workbook()
    sheet1 = wb.add_sheet('Sheet 1')

    #Insert Headlines for Cells into Excel
    sheet1.write(0, 0, "0")
    sheet1.write(0, 1, "a")
    sheet1.write(0, 2, "b")
    sheet1.write(0, 3, "c")
    sheet1.write(0, 4, "d")

    #Save Result    
    wb.save(dest_filename)
    print(str("Complete"))
    print("\n")

    book = xlrd.open_workbook('empty_book.xlsx')
    sheet = book.sheet_by_index(0)

    #Count of rows
    count = 0
    for row in range(sheet.nrows):
        for col in sheet.row_values(row):
            if col.strip() != '':
                count  = 1
            print(count)

    #Insert into file.txt
    with  open("python.txt", "a") as file:
        content = str(Tid)   '_'   str(id)   '\n'
        print("Appended!")
        file.write(content)
        file.close()


    workbook = xlrd.open_workbook("empty_book.xlsx", "rb")
    sheets = workbook.sheet_names()
    sh = workbook.sheet_by_name(dest_filename_sheet)
    for rownum in range(0, sh.nrows): #skipping header of the xlsx
        xz = sh.cell(rownum, 0)
        xz_int = int(xz.value)
        print(xz_int)
        print("\n")
        if xz_int == counter1:
            counter1  = 1
            print("Hi Mathematics0")     
        else:
            xz_int  = 1
            print("Swag")
            print("\n")

        if xz_int == counter1:
            print("Hi Mathematics1")
            #Insert posted values
            sheet1.write(counter1, 0, str(a))
            sheet1.write(counter1, 1, str(b))
            sheet1.write(counter1, 2, str(c))
            sheet1.write(counter1, 3, str(d))
            wb.save(dest_filename)
            print("Inserted into1")
            print("\n")
            counter1  = 1
            xz_int  = 1
        if xz_int == counter1:
            print("Hi Mathematics2")
            print("\n")  
            sheet1.write(counter1, 0, str(a))
            sheet1.write(counter1, 1, str(b))
            sheet1.write(counter1, 2, str(c))
            sheet1.write(counter1, 3, str(d))
            wb.save(dest_filename)
            print("Inserted into")
            counter1  = 1
            xz_int  = 1
        else:
            print("Swag2")
            print("\n")

    return render_template('index.html')



## END_end

I want to be able to read the current index in column[0, X] in the file.xlms and create an entry to the position/value of column[0, X 1]. The current Excel-result and terminal output I be getting are:

Excel Result

I know it's my for loop that's too crazy. But I hope you get the idea of what I'm trying to do. I want to add new lines in Excel with the values from every entry, also without deleting the old ones. Thanks anyway :)

CodePudding user response:

Reference to Python usage of len() to get number of array indexes

import pandas as pd
df = pd.ExcelFile('file_name.xlsx').parse('sheet_name')
x=[]
x.append(df['column_name'])
x.clear()
x.extend(df['column_name'])
print(len(x))
  • Related