如何使用python openpyxl在excel中插入A列到J列的数据

2024-04-26 23:56:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个函数,该函数将检查行中的单元格是否为None,如果为None,它将插入functions参数中的数据。 该函数将从A列迭代到J列,但是,当我运行该函数时,会出现以下错误:

Traceback (most recent call last):
  File "records.py", line 54, in <module>
    check_rows(3, "06so", "necklace", "somenecklace", 2, 10, 20, "Card", "Bank", "SomeBank")
  File "records.py", line 39, in check_rows
    j = st1["J" + str(i)]
  File "/home/akeno/.local/lib/python3.8/site-packages/openpyxl/worksheet/worksheet.py", 
line 290, in __getitem__
    min_col, min_row, max_col, max_row = range_boundaries(key)
  File "/home/akeno/.local/lib/python3.8/site-packages/openpyxl/utils/cell.py", line 135, in 
range_boundaries
    raise ValueError(msg)
ValueError: J<Cell 'Records'.I2> is not a valid coordinate or range

代码如下:

import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
import datetime

wb = load_workbook("excel.xlsx")

st1 = wb.active
st1 = wb["Records"]

st1["A1"] = "Date"
st1.column_dimensions["A"].width = 23
st1["B1"] = "Code"
st1["C1"] = "Family"
st1["D1"] = "Product"
st1.column_dimensions["D"].width = 30
st1["E1"] = "Quantity"
st1["F1"] = "Price"
st1["G1"] = "Total"
st1["H1"] = "Payment"
st1["I1"] = "Form"
st1["J1"] = "Deposit"
st1["K1"] = "Cod.Client"

def check_rows(counter, cod, fam, prod, quant, pric, total, pay, form, dep):
    a, b, c, d, e, f, g, h, i, j = '','','','','','','','','',''

    for i in range(2,counter):

        if (st1["A" + str(i)].value and st1["B" + str(i)].value and st1["C" + str(i)].value 
and st1["D" + str(i)].value and st1["E" + str(i)].value and st1["F" + str(i)].value and 
st1["G" + str(i)].value and st1["H" + str(i)].value and st1["I" + str(i)].value and st1["J" 
+ str(i)].value) == None:
            a = st1["A" + str(i)]
            b = st1["B" + str(i)]
            c = st1["C" + str(i)]
            d = st1["D" + str(i)]
            e = st1["E" + str(i)]
            f = st1["F" + str(i)]
            g = st1["G" + str(i)]
            h = st1["H" + str(i)]
            i = st1["I" + str(i)]
            j = st1["J" + str(i)]
        
            a.value = datetime.datetime.today()
            b.value = cod
            c.value = fam
            d.value = prod
            e.value = quant
            f.value = pric
            g.value = total
            h.value = pay
            i.value = form
            j.value = dep
        
    wb.save(filename = "excel.xlsx")

check_rows(3, "06so", "necklace", "somenecklace", 2, 10, 20, "Card", "Bank", "SomeBank")

计数器i用于控制循环流,例如,我要填充多少行。 有人能帮忙吗? 无论如何谢谢你


Tags: and函数inpyimportvaluecheckline