0

如何以编程方式删除打开文档电子表格中的工作表,最好是在 Python 中?

我查看了https://pypi.python.org/pypi/pyexcel-ods/0.0.3但我没有看到任何有关如何执行此操作的文档。

如果我运行data.update({"WORKSHEET1": "",}),我只是删除我想保留的工作表和我想完全删除的 WORKSHEET1 的内容。

谢谢

4

2 回答 2

1

简短的回答是:将其作为 OrderedDict 读回,然后删除键(您的工作表名称)并将修改后的字典保存到文件中。

解决方案 A. 使用 ezodf 的示例解决方案

>>> import ezodf
>>> doc = ezodf.opendoc("sample.ods")
>>> list(doc.sheets.names())
['Sheet1', 'Sheet2', 'Sheet3']
>>> del doc.sheets[1]
>>> doc.save()
>>> exit()

更多文档可以在这里找到

解决方案 B. 使用 pyexcel-ods 的示例解决方案: 1. 让我们设置示例文件:

>>> from pyexcel_ods import ODSWriter
>>> from collections import OrderedDict
>>> data = OrderedDict()
>>> data.update({"Sheet 1": [[1, 2, 3], [4, 5, 6]]})
>>> data.update({"Sheet 2": [["row 1", "row 2", "row 3"]]})
>>> writer = ODSWriter("your_file.ods")
>>> writer.write(data)
>>> writer.close()

2. 让我们回顾一下:

>>> from pyexcel_ods import ODSBook
>>> book2 = ODSBook("your_file.ods")
>>> data=book2.sheets()
>>> data
OrderedDict([(u'Sheet 1', [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), (u'Sheet 2', [[u'row 1', u'row 2', u'row 3']])])

3. 现在删除“Sheet 1”:

>>> data.pop('Sheet 1')
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
>>> data
OrderedDict([(u'Sheet 2', [[u'row 1', u'row 2', u'row 3']])])

4. 然后将其保存到您选择的文件中:

>>> writer2=ODSWriter("your_file2.ods")
>>> writer2.write(data)
>>> writer2.close()

5. 让我们回读并验证:

>>> book3=ODSBook("your_file2.ods")
>>> book3.sheets()
OrderedDict([(u'Sheet 2', [[u'row 1', u'row 2', u'row 3']])])
于 2015-01-22T15:31:57.063 回答
0

原来的问题是:

在打开的文档电子表格中删除工作表

答:与 StarBasic 中的相同:

# get the model of document
    model = XSCRIPTCONTEXT.getDocument()
# get all sheets
    sheets = model.Sheets
# delete a sheet by name
    sheets.removeByName("Sheet2") 

无需使用外部库、导入、字典、...

这有帮助吗?

于 2015-01-31T07:19:19.720 回答