Openpyxl不会保存文件

时间:2017-11-09 13:59:02

标签: python excel openpyxl

出于某种原因,Openpyxl不会在程序结束时保存xlsx文件。 我试图从文件中读取测量值,每一行都是不同的测量值。我想把它们写成excel,以便以后更容易使用这些数据。一切似乎都有效,但最终数据没有保存,如果我创建了应保存更改的新文件,则不会创建。

from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook(filename='Data_Base.xlsx')
sheet = wb.worksheets[0]
BS = []
Signal = []
with open('WifiData2.txt') as f:
 for line in f:
    y = int(line.split('|')[0].split(';')[3])
    x = int(line.split('|')[0].split(';')[2])
    floor = int(x = line.split('|')[0].split(';')[1])
    data = line.split("|")[1].strip()
    measurements = data.split(";")
    for l in measurements:
        raw = l.split(" ")
        BSSID = raw[0]
        signal_strength = raw[1]
        print(signal_strength)
        BS.append(BSSID)
        Signal.append(signal_strength)

    for row_num in range(sheet.max_row):
        num = row_num
        if row_num > 1:
            test_X = int(sheet.cell(row=row_num, column=4).value)
            test_Y = int(sheet.cell(row=row_num, column=3).value)
            test_floor = int(sheet.cell(row=row_num, column=2).value)
            if (test_X == x and test_Y == y and test_floor == floor):
                nr = nr + 1

    if (nr > 3):
        q = 1

    if (q == 0):

        sheet.cell(row=sheet.max_row+1, column = 2, value = floor)
        sheet.cell(row=sheet.max_row + 1, column=3, value=x)
        sheet.cell(row=sheet.max_row + 1, column=4, value=y)
        sheet.cell(row=sheet.max_row + 1, column=2, value=sheet.max_row)
        for element in BS:
            nr = 0
            for col in sheet.max_column:
                if BS[element] == sheet.cell(row=1, column=col).value:
                    sheet.cell(row=sheet.max_row + 1, column=col, value=Signal[element])
                    nr = 1
            if (nr == 0):
                sheet.cell(row=1, column=sheet.max_column+1, value=BS[element])
                sheet.cell(row=sheet.max_row+1, column=sheet.max_column + 1, value=BS[element])

    Signal.clear()
    BS.clear()
wb.save('Data_Base1.xlsx')

奇怪的是,如果我先保存工作簿,它将创建该文件。当然,它并不适合我,因为我想做的任何改变都不会成功。当我用xlrd / wt / utils组合尝试它时,我有类似的问题。 any1知道问题出在哪里吗?

2 个答案:

答案 0 :(得分:0)

使用绝对路径而不是相对路径可以解决问题!

答案 1 :(得分:-1)

添加

wb.template = False

之前

wb.save('Filename.xlsx')