在IronPython中用openpyxl保存工作簿

1 投票
1 回答
1963 浏览
提问于 2025-04-18 04:37

我在用openpyxl保存Excel文件时遇到了问题,这个代码是在一个嵌入了.NET 4.0应用程序的IronPython运行环境中运行的。不过,当我在IronPython解释器中运行同样的代码时,没有任何错误,保存也成功。实际上,代码简单得很,如下所示:

import sys
sys.path.append(r'c:\python27\lib\site-packages')
import openpyxl
wb=openpyxl.Workbook()
wb.save(r'c:\save\to\somewhere.xlsx')

但是在.NET应用程序中运行这段代码时,我得到了以下的错误信息:

an error occurred saving to "c:\_kevin\test.xlsx": Traceback (most recent call last):
    File "C:\path\to\script\file.py", line 582, in __write_logs_to_excel
    wb.save(outfile)
  File "C:\Python27\Lib\site-packages\openpyxl\workbook.py", line 265, in save
    save_workbook(self, filename)
  File "C:\Python27\Lib\site-packages\openpyxl\writer\excel.py", line 187, in save_workbook
    writer.save(filename)
  File "C:\Python27\Lib\site-packages\openpyxl\writer\excel.py", line 170, in save
    self.write_data(archive)
  File "C:\Python27\Lib\site-packages\openpyxl\writer\excel.py", line 76, in write_data
    shared_string_table = self._write_string_table(archive)
  File "C:\Python27\Lib\site-packages\openpyxl\writer\excel.py", line 105, in _write_string_table
    archive.writestr(ARC_SHARED_STRINGS,
  File "C:\Python27\Lib\site-packages\openpyxl\writer\strings.py", line 47, in write_string_table
    start_tag(doc, 'sst', {'xmlns':
  File "C:\Python27\Lib\site-packages\openpyxl\shared\xmltools.py", line 172, in start_tag
    doc.startElementNS((namespace, name), name, attr2)
  File "C:\Python27\Lib\xml\sax\saxutils.py", line 165, in startElementNS
    def startElementNS(self, name, qname, attrs):
  File "C:\Python27\Lib\xml\sax\saxutils.py", line 102, in write
    def write(self, s):
TypeError: expected long, got NoneType

我用以下代码初始化了Python引擎:

_pythonEngine = Python.CreateEngine(engineDict);
_memStream = new System.IO.MemoryStream();
_streamWriter = new util.EventRaisingStreamWriter(_memStream);               
_pythonEngine.Runtime.IO.SetErrorOutput(_memStream, _streamWriter);
_pythonEngine.Runtime.IO.SetOutput(_memStream, _streamWriter);

_streamwriter是一个用来把事件输出发送到文本框的工具。

为什么我在解释器中可以顺利保存,而在引擎中却不行呢?我尝试过不重定向输出流,但还是出现了同样的错误。

  • IronPython版本 = 2.7.0.40(文件版本2.7.4.1000)
  • openpyxl版本 = 1.8.5
  • Python版本 = 2.7.6

谢谢。

1 个回答

0

看起来你在用CPython的标准库的一部分:

File "C:\Python27\Lib\xml\sax\saxutils.py", line 165, in startElementNS
    def startElementNS(self, name, qname, attrs):
  File "C:\Python27\Lib\xml\sax\saxutils.py", line 102, in write
    def write(self, s):
TypeError: expected long, got NoneType

IronPython的标准库稍微有点不同。当你在解释器下运行时,它可能会使用IronPython的标准库,但在你的程序中,它使用的是CPython的库。

在嵌入的时候,你可以用 engine.SetSearchPaths 来控制搜索路径。

撰写回答