Skip to main content
 首页 » 编程设计

python之从 Excel 生成一个 JSON 文件以在 Python 中读取

2024年11月01日8开发

我有一个很大的 Excel 文件,其中包含多个表格。
我能够使用 VBA 代码中的 ADODB.Stream 将它们序列化为 JSON:

这是 VBA 代码:

Dim st As ADODB.Stream 
  ' create a stream object 
Set st = New ADODB.Stream 
' set properties 
st.Charset = "utf-8" 
st.Type = adTypeText 
' open the stream object and write some text 
st.Open 
st.WriteText myString 
st.SaveToFile filepath, adSaveCreateOverWrite 
st.Close 

现在我想用 Python 读取它以将其传递给数据框:

这是 Python 代码:

import JSON 
with open(myfilecomplete) as f: 
    data = json.load(f) 

我收到这个错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 407330: character maps to

文件很大(1MB 文本)。我什至不知道如何找到字符 407330。

此外,我应该以最常见的编码形式 uft-8 写入光盘。对吧?

为什么 JSON 不能解解码 utf-8?

回答后编辑/警告:不要尝试从 Excel 手动序列化 JSON 文件。这最终几乎总是会出错。使用适当的库来执行此操作,如 here :

请您参考如下方法:

你明白了:

 
with open(myfilecomplete, encoding='utf-8-sig') as f: 
    data = json.load(f) 

Here some documentation