openpyxl将列变成行

时间:2019-10-03 05:58:43

标签: python excel openpyxl

我有3个工作表的excel工作簿origin.xlsx。我想遍历所有工作表中特定列的所有单元格(例如,列“ A”),复制每个单元格的值并将它们全部(一个接一个地)传递到另一本工作簿destination.xlsx的行中。即从多个工作表的列中制作一行。 但是,我的代码仅将origin.xlsx

中3列中每列的最后一个单元格的值放在一行中
import openpyxl
wb = openpyxl.load_workbook('origin.xlsx')
g_sheet=wb.sheetnames
print(g_sheet)
for i in g_sheet:
    print(i)
    ws = wb.get_sheet_by_name(i)
    print(ws)
    for row in range(1, ws.max_row + 1):
        for column in "A":
            cell_name = "{}{}".format(column, row)
            print(ws[cell_name].value)
        wb = openpyxl.load_workbook('destination.xlsx')
        wss = wb.active
        wss.cell(row=1, column=ws.max_column + 1, value=ws[cell_name].value)
        wb.save(filename)

2 个答案:

答案 0 :(得分:1)

您可以首先使用单独的打印机打开源文件和目标文件,遍历源文件中的工作表,然后将所选row的所有column值附加到目标文件中,如下所示,

# _s denotes source/origin and _d -> destination
wb_s = openpyxl.load_workbook('origin.xlsx')

# create worrkbook 'destination.xlsx' if it does not exist
wb_d = openpyxl.Workbook()
wb_d.save('destination.xlsx')
ws_d = wb_d.active

row_num = 1
for sheet in wb_s.sheetnames:
    ws_s = wb_s[sheet]
    for cell_s in ws_s['A']: # if 'A' is the column to copy
#         if cell_s.row > 1:    to avoid  writing column headings  to destination file if source column has column heading
        ws_d.cell(row=row_num, column=1, value=cell_s.value) # column =1 will write the selected values to column 'A
        row_num+=1
wb_d.save('destination.xlsx')

答案 1 :(得分:1)

from openpyxl import load_workbook, Workbook
wb1 = openpyxl.load_workbook('origin.xlsx', read_only=True)
wb2 = Workbook()

ws1 = wb1.active
ws2 = wb2.active

cols = ws1.iter_cols(min_col=1, max_col=1, values_only=True)
for col in cols:
    ws2.append(col)