簡體   English   中英

將數據寫入Excel電子表格-為什么它會每隔第二行跳過一次?

[英]Writing data into an Excel spreadsheet - why does it skip every second line?

我在Python中使用openpyxl將一些數據從txt文件復制到Excel電子表格中。 以下代碼盡管簡單,卻跳過了第二行,僅寫入電子表格中的其他每一行。 有人可以幫忙告訴我我在做什么錯嗎?

line_index = 1  # To keep track of the current line's "index" in the file
    for l in f:
        line = l.split(",")

    # Transfer needed values into Spreadsheet, leaving the first two columns
    # empty so they can be populated later, because openpyxl doesn't support
    # easy insertion of columns.
        for i in range(len(line)):
            ws.cell(row=line_index, column=i+3).value = line[i]            
        line_index += 1

首先,如果需要計數器,請使用enumerate()函數以提高可靠性。 其次,不用調用ws.cell()而是在行之前添加兩個空值[None]*2以便可以使用ws.append() 第三,openpyxl v2.5確實支持列和行的插入和刪除。

TWO_COLS = [None] * 2
for line in f:
    line = TWO_COLS + line.split()
    ws.append(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM