简体   繁体   中英

Openpyxl formatting cells with the number 1 with a negative number and showing all HashTags

this is a very unique issue so I'm hoping some of you can help me out with this!

So this is a multipart issue, the first issue is that the original code that handles my excel manipulations is incorrectly formatting some columns as a date column, that is not what I'm trying to resolve here, but it might be important for backstory. It seems to be formatting the columns for epoch time, so having the number 1 in the column would be displayed as 1900 or so. For the sake of the rest of this question, lets assume that this incorrect date format is OK and that I'll just be manually changing the format on excel later.

My more prominent issue arises as follows; openpyxl (or my code mistakes) seem to setting cells that contain the number 1, to -5. This looks like the image below, all of the HASHTAG cells are supposed to have "1" inside.

Anything that is formatted as a date is completely fine, and will change to their actual number as soon as I change the column format to number. The ones with the hashtags will change to -5, or some negative number as follows;

在此处输入图像描述

I tried iterating through all the cells manually and fixing it with the following code;

import datetime
from openpyxl import load_workbook, worksheet

date_string = datetime.date.today().strftime("%Y%B%d")
name_string = 'REDACTED'
wb = load_workbook(filename = name_string)
ws = wb.get_sheet_by_name(name = 'vInfo')
for row in ws.iter_rows():
    for cell in row:
        if (str(cell.value) == "-5"): # Or whatever the number was displaying on the sheet at the t ime)
            print(cell.value)
            cell.number_format = '0'
            cell.value = int(1)

wb.save(name_string)
print("saved at "+name_string)

When I ran this, there was no change, it seems like the cell.value is not ACTUALLY that negative number and seems to be some kind of error? Furthermore, each time the workbook is saved, the negative number decreases by one.

I cannot provide the initial code that generates the excel file (under NDA), but I hope I've explained enough for you to have an idea of what I'm facing!

I am at a complete loss and I'm really hoping someone can point out what's wrong, and I thank you so much for your time!

Microsoft Excel says "Dates that are negative or too large will be shown as #########"

For example, i have entered a negative number -2 in a cell

例子

you can change the cell format to text to show the negative number.

from openpyxl.styles import numbers
cell.number_format = numbers.FORMAT_TEXT

or for your code

cell.number_format = '@'
cell.value = "1"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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