Read_excel(), 字符串的一列,但在excel 格式中,它是日期并导致错误

Read_excel(), A column of string, but in excel format, it is date and cause error

我的data.xlsx是这样的

 Number  Grade
3217839     A
7893242     B
3782195     C
      0     D

但是,在excel中,Number列的文本格式是“Short Date”,导致数据变成

  Number  Grade
 #######     A
 #######     B
 #######     C
00-01-00     D

我用的是df = pd.read_csv("data.xlsx"),结果报错显示NaN

错误(只显示A2):

UserWarning: Cell A2 is marked as a date but the serial value 321783921 is outside the limits for dates. 
The cell will be treated as an error. warn(msg)

     Number Grade
0       NaN     A
1       NaN     B
2       NaN     C
3  00:00:00     D

我试过 df = pd.read_csv("data.xlsx", coverters={"Number": str})。结果还是一样。无需手动更改 excel?

中的格式即可解决此问题的任何方法

Excel 表示具有“序列号”的日期,从 1 代表 01.01.1900 到 2958465 代表 31.12.9999。所以 Pandas 和 Excel 都抱怨你的值,因为它们不能被解释为日期。改一下单元格格式,简直就是错误

如果您没有修改然后保存 wb 的权限,您可以使用 xlwings 从 python 中调用 Excel。打开 wb,将单元格的数字格式更改为 'General',select 您的范围,关闭 wb 并退出应用程序。

# assuming data in wb.sheets[0].range('A1:B5')

import xlwings
import pandas as pd

my_file = 'data.xlsx'

excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open(my_file, read_only=True)

sht = excel_book.sheets[0]
sht.range('A1:A5').number_format = 'General'

my_cols = sht.range('A1:B1').value
my_range = sht.range('A2:B5').value

excel_book.close()
excel_app.quit()

df = pd.DataFrame(my_range, columns=my_cols)

# =============================================================================
# 
# display(df)
# 
#       Number Grade
# 0  3217839.0     A
# 1  7893242.0     B
# 2  3782195.0     C
# 3        0.0     D
# 
# =============================================================================