[英]Python-Excel: How to write lines of a row to an existing excel file?
我已經搜索了該站點,但是找不到與以下問題相關的任何內容。
我有一個現有的電子表格,每天將要從中提取數據,電子表格中的信息將每天更改。
我想要做的是創建一個文件,該文件跟蹤該單元格中的某些信息,我希望它從電子表格中提取數據並將其寫入另一個電子表格。 將數據添加到新的電子表格中不應覆蓋現有數據。對此,我將非常感謝。 參見下面的代碼:
import os
import openpyxl
import xlrd
wb=openpyxl.load_workbook('Test_shorts.xlsx','r')
sheet = wb.active
rows = sheet.max_row
col = sheet.max_column
rows = rows+1
print rows
new =[]
for x in range (2, 3):
for y in range(1,10):
z= sheet.cell(row=x,column=y).value
new.append(z)
print(new)
如果要復制整個工作表,則可以直接使用copy_worksheet()
函數。 它將創建活動工作表的副本。
我不知道您的數據,但我相信您可以自己完成。 希望這會有所幫助
from openpyxl import load_workbook
file_name = "Test_shorts.xlsx"
wb = load_workbook(file_name)
sheet = wb.active
target = wb.copy_worksheet(sheet)
# you can code to append new data here
new = wb.get_sheet_by_name(target.title) # to get copied sheet
for x in range (2, 3):
for y in range(1,10):
print(x,y)
z= sheet.cell(row=x,column=y).value
new.append(z)
wb.save(file_name)
如前所述,需要一個單元格循環,因此我對您的代碼做了一些改動。
from openpyxl import load_workbook
file_name = "Test_shorts.xlsx"
wb = load_workbook(file_name)
current_sheet = wb.active
new_sheet = wb.create_sheet("New", 1)
for row in current_sheet.rows:
col = 0 # set the column to 0 when 1 row ends
for cell in row:
col += 1 # cell.column will return 'ABC's so I defined col for the column
new_sheet.cell(cell.row, col, cell.value)
wb.save(file_name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.