简体   繁体   English

如何使用 Openpyxl 更新现有的 Excel.xlsx 文件?

[英]How to update existing Excel .xlsx file using Openpyxl?

I am trying to make this code work, the problem is that in the excel file the print (...) data is not written, I have tried to use ws.appened (...) but without results.我正在尝试使这段代码工作,问题是在 excel 文件中未写入print (...)数据,我尝试使用ws.appened (...)但没有结果。

import arcpy
from openpyxl import Workbook
wb = Workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws =  wb.active
rows = arcpy.SearchCursor("C:/Users/Hp/Desktop/ejemplo/VH_Dissolve.shp",
                          fields="COLOR; INTERNO_DE; CLASE_DEMA; COUNT_AREA; SUM_AREA; SUM_LENGTH",
                          sort_fields="COLOR 222; INTERNO_DE A")
# COLOR, INTERNO_DE, CLASE_DEMA, COUNT_AREA, SUM_AREA y SUM_LENGTH.
for row in rows:
    print("Color: {0}, Interno: {1}, Clase:{2}, ContarA: {3}, SumarA: {4}, SumarL: {5}".format(
        row.getValue("COLOR"),
        row.getValue("INTERNO_DE"),
        row.getValue("CLASE_DEMA"),
        row.getValue("COUNT_AREA"),
        row.getValue("SUM_AREA"),
        row.getValue("SUM_LENGTH")))
wb.save('VINCULACION_S.xlsx')

I have also tried to locate the results data in the excel file from cell B3: G3 onwards but I can't find it.我还尝试从单元格 B3:G3 开始在 excel 文件中找到结果数据,但我找不到它。

I got this code as a solution to the post我得到了这个代码作为帖子的解决方案

import arcpy
import openpyxl as px

def main():
    wb = px.load_workbook(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsx")
    ws = wb['VINCULACION_SH_NUE']
    in_features = r"C:\Users\Hp\Desktop\Ejemplo\VH_Dissolve.shp"

    row_num = 3
    with arcpy.da.SearchCursor(
        in_features,
        ["COLOR", "INTERNO_DE", "CLASE_DEMA", "COUNT_AREA", "SUM_AREA", "SUM_LENGTH"],
    ) as cursor:
        for row in cursor:
            ws.cell(row=row_num, column=2).value = row[0]
            ws.cell(row=row_num, column=3).value = row[1]
            ws.cell(row=row_num, column=4).value = row[2]
            ws.cell(row=row_num, column=6).value = row[3]
            ws.cell(row=row_num, column=7).value = row[4]
            ws.cell(row=row_num, column=8).value = row[5]
            row_num += 1
    wb.save(r"C:\Users\Hp\Desktop\Ejemplo\VINCULACION_S.xlsx")


if __name__ == "__main__":
    main()

Try deleting the content in the existing sheet.尝试删除现有工作表中的内容。 Save and reload it.保存并重新加载它。

import arcpy
from openpyxl import Workbook
wb = Workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws =  wb.active
k = 100     # approximate no of rows in existing sheet
for i in range(k):
    ws.delete_rows(0)
wb.save()
wb = load_workbook("C:/Users/Hp/Desktop/ejemplo/VINCULACION_S.xlsx")
ws = wb.active

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM