打开文件的不同方式
Contents
[
Hide
]
使用Aspose.Cells很容易打开文件,例如检索数据,或使用设计模板加快开发过程。
通过路径打开文件
开发人员可以通过在 Workbook 类构造函数中指定本地计算机上文件路径来打开 Microsoft Excel 文件。只需将路径作为 string 传递给构造函数。Aspose.Cells 将自动检测文件格式类型。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aspose.cells | |
from aspose.cells import Workbook | |
# Opening a File via a Path | |
# The path to the documents directory. | |
dataDir = "" | |
# Opening through Path | |
# Creating a Workbook object and opening an Excel file using its file path | |
workbook = Workbook(dataDir + "Input.xlsx") | |
print("Workbook opened using path successfully!") |
通过流打开文件
也可以通过流简单地打开 Excel 文件。为此,使用接受包含文件的 BufferStream 对象的构造函数的重载版本。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
import aspose.cells | |
from aspose.cells import Workbook, CellsHelper, License, SaveFormat | |
with open('Input.xlsx', 'rb') as file: | |
input_stream = io.BytesIO(file.read()) | |
workbook = Workbook(input_stream) | |
out_stream = io.BytesIO() | |
workbook.save(out_stream, SaveFormat.XLSX) | |
out_bytes = out_stream.getvalue() | |
print(out_bytes) | |
out_stream.close() | |
input_stream.close() | |
print("Workbook opened using stream successfully!") |
仅打开带有数据的文件
要仅使用LoadOptions和LoadFilter类打开带有数据的文件,以设置这些类的相关属性和选项为需要加载的模板文件。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aspose.cells | |
from aspose.cells import Workbook, LoadOptions, LoadFormat, LoadFilter, LoadDataFilterOptions | |
# Opening a File with Data only | |
# The path to the documents directory. | |
dataDir = "" | |
# Load only specific sheets with data and formulas | |
# Other objects, items etc. would be discarded | |
# Instantiate LoadOptions specified by the LoadFormat | |
loadOptions = LoadOptions(LoadFormat.XLSX) | |
# Set LoadFilter property to load only data & cell formatting | |
loadOptions.load_filter = LoadFilter(LoadDataFilterOptions.CELL_DATA) | |
# Create a Workbook object and opening the file from its path | |
workbook = Workbook(dataDir + "Input.xlsx", loadOptions) | |
print("File data imported successfully!") |
如果尝试使用Aspose.Cells打开非本机Excel文件或其他文件格式(例如PPT/PPTX,DOC/DOCX等),将引发异常。
Workbook的构造函数在加载大型电子表格时可能会引发System.OutOfMemoryException异常。该异常表明可用内存不足以完全将电子表格加载到内存中,因此必须在启用内存首选项的情况下加载电子表格。