打开不同格式的文件

打开Excel文件的简单方法

通过路径打开

使用文件路径来打开Microsoft Excel文件,当创建Workbook类的实例时,将文件路径作为参数传递。以下示例代码演示了如何使用文件路径打开Excel文件。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningFilesThroughPath.class) + "files/";
// Opening from path.
// Creating an Workbook object with an Excel file path
Workbook workbook1 = new Workbook(dataDir + "Book1.xlsx");
// Print message
System.out.println("Workbook opened using path successfully.");

通过流打开

有时,要打开的Excel文件存储为流。在这种情况下,与使用文件路径打开文件类似,实例化Workbook类时将流作为参数传递。以下示例代码演示了如何使用流打开Excel文件。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningFilesThroughStream.class) + "loading_saving/";
// Opening workbook from stream
// Create a Stream object
FileInputStream fstream = new FileInputStream(dataDir + "Book2.xls");
// Creating an Workbook object with the stream object
Workbook workbook2 = new Workbook(fstream);
fstream.close();
// Print message
System.out.println("Workbook opened using stream successfully.");

打开不同版本的 Microsoft Excel 文件

用户可以使用LoadOptions类指定Excel文件的格式,使用LoadFormat枚举。

LoadFormat枚举包含许多预定义的文件格式,其中一些如下所示。

格式类型 描述
Csv 表示CSV文件
Excel97To2003 表示Excel 97-2003文件
Xlsx 表示Excel 2007/2010/2013/2016/2019和Office 365 XLSX文件
Xlsm 代表Excel 2007/2010/2013/2016/2019和Office 365的XLSM文件
Xltx 代表Excel 2007/2010/2013/2016/2019和Office 365模板XLTX文件
Xltm 代表Excel 2007/2010/2013/2016/2019和Office 365宏启用的XLTM文件
Xlsb 代表Excel 2007/2010/2013/2016/2019和Office 365二进制XLSB文件
SpreadsheetML 代表SpreadsheetML文件
Tsv 代表分隔值文件
TabDelimited 代表分隔符文本文件
Ods 代表ODS文件
Html 代表HTML文件
Mhtml 代表MHTML文件

打开Microsoft Excel 95/5.0文件

要打开Microsoft Excel 95文件,请使用Workbook实例化模板文件的路径或流。可以从以下链接下载示例文件以测试代码:

Excel95_5.0.xls

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Opening Microsoft Excel 97 Files
// Creating an EXCEL_97_TO_2003 LoadOptions object
// Creating an Workbook object with excel 97 file path and the
// loadOptions object
new Workbook(srcDir + "Excel95_5.0.xls");

打开Microsoft Excel 97或更高版本的XLS文件

要打开Microsoft Excel XLS 97或更高版本的XLS文件,请使用Workbook实例化模板文件的路径或流。或者使用LoadOptions方法,并在LoadFormat枚举中选择EXCEL_97_TO_2003值。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningMicrosoftExcel972003Files.class) + "loading_saving/";
// Opening Microsoft Excel 97 Files
// Createing and EXCEL_97_TO_2003 LoadOptions object
LoadOptions loadOptions1 = new LoadOptions(LoadFormat.EXCEL_97_TO_2003);
// Creating an Workbook object with excel 97 file path and the
// loadOptions object
Workbook workbook3 = new Workbook(dataDir + "Book_Excel97_2003.xls", loadOptions1);
// Print message
System.out.println("Excel 97 Workbook opened successfully.");

打开Microsoft Excel 2007或更高版本的XLSX文件

要打开Microsoft Excel 2007或更高版本的XLSX文件,请使用Workbook实例化模板文件的路径或流。或者使用LoadOptions类,并在LoadFormat枚举中选择XLSX值。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningMicrosoftExcel2007XlsxFiles.class) + "loading_saving/";
// Opening Microsoft Excel 2007 XLSX Files. Createing and XLSX LoadOptions object
LoadOptions loadOptions2 = new LoadOptions(LoadFormat.XLSX);
// Creating an Workbook object with 2007 xlsx file path and the loadOptions object
Workbook workbook4 = new Workbook(dataDir + "Book_Excel2007.xlsx", loadOptions2);
// Print message
System.out.println("Excel 2007 Workbook opened successfully.");

打开具有不同格式的文件

Aspose.Cells允许开发人员打开不同格式的电子表格文件,例如SpreadsheetML、CSV、制表符分隔文件。要打开这些文件,开发人员可以使用与打开不同Microsoft Excel版本文件相同的方法。

打开电子表格 ML 文件

SpreadsheetML文件是您电子表格的XML表示,包括有关电子表格的所有信息,如格式、公式等。自Microsoft Excel XP以来,Microsoft Excel还增加了将电子表格导出为SpreadsheetML文件的XML导出选项。

要打开SpreadsheetML文件,请使用LoadOptions类,并在LoadFormat枚举中选择SPREADSHEET_ML值。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningSpreadsheetMLFiles.class) + "loading_saving/";
// Opening SpreadsheetML Files
// Creating and EXCEL_2003_XML LoadOptions object
LoadOptions loadOptions3 = new LoadOptions(LoadFormat.SPREADSHEET_ML);
// Creating an Workbook object with SpreadsheetML file path and the
// loadOptions object
Workbook workbook5 = new Workbook(dataDir + "Book3.xml", loadOptions3);
// Print message
System.out.println("SpreadSheetML format workbook has been opened successfully.");

打开 CSV 文件

逗号分隔的值(CSV)文件包含由逗号分隔或分隔的记录值。在 CSV 文件中,数据以字段由逗号字符分隔并由双引号字符引用的表格格式存储。如果字段的值包含双引号字符,则用一对双引号字符进行转义。您还可以使用 Microsoft Excel 将电子表格数据导出为 CSV 文件。

要打开CSV文件,请使用 LoadOptions 类并选择在 LoadFormat 枚举中预定义的 CSV 值。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningCSVFiles.class) + "loading_saving/";
// Opening CSV Files
// Creating and CSV LoadOptions object
LoadOptions loadOptions4 = new LoadOptions(LoadFormat.CSV);
// Creating an Workbook object with CSV file path and the loadOptions
// object
Workbook workbook6 = new Workbook(dataDir + "Book_CSV.csv", loadOptions4);
// Print message
System.out.println("CSV format workbook has been opened successfully.");

打开 CSV 文件并替换无效字符

在 Excel 中,当打开具有特殊字符的 CSV 文件时,这些字符会被自动替换。Aspose.Cells API 也会执行相同的操作,如下面给出的代码示例所示。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Source directory
String dataDir = Utils.getSharedDataDir(OpeningCSVFilesAndReplacingInvalidCharacters.class) + "LoadingSavingConvertingAndManaging/";
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV);
//Load CSV file
Workbook workbook = new Workbook(dataDir + "[20180220142533][ASPOSE_CELLS_TEST].csv", loadOptions);
System.out.println(workbook.getWorksheets().get(0).getName()); // (20180220142533)(ASPOSE_CELLS_T
System.out.println(workbook.getWorksheets().get(0).getName().length()); // 31
System.out.println("CSV file opened successfully!");

使用首选解析器打开 CSV 文件并不总是必需的。有时导入 CSV 文件会得到意外的输出,例如日期格式不符合预期或空字段的处理方式不同。为此可以使用 TxtLoadOptions.PreferredParsers 来提供自己喜欢的解析器,以根据要求解析不同的数据类型。以下示例代码演示了首选解析器的用法。

并非总是需要使用默认的解析器设置来打开CSV文件。有时导入CSV文件的输出与预期不同,例如日期格式不符合期望或空字段处理方式不同。为此,可使用 TxtLoadOptions.PreferredParsers 来提供自己偏好的解析器,以根据需求解析不同的数据类型。以下示例代码演示了首选解析器的用法。  

可以从以下链接下载示例源文件和输出文件,以测试此功能。

samplePreferredParser.csv

outputsamplePreferredParser.xlsx

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
class TextParser implements ICustomParser
{
@Override
public Object parseObject(String s) {
return s;
}
@Override
public String getFormat() {
return "";
}
}
class DateParser implements ICustomParser {
@Override
public Object parseObject(String s) {
Date myDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
myDate = formatter.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return myDate;
}
@Override
public String getFormat() {
return "dd/MM/yyyy";
}
}
public class OpeningCSVFilesWithPreferredParser {
//Source directory
private static String sourceDir = Utils.Get_SourceDirectory();
private static String outputDir = Utils.Get_OutputDirectory();
public static void main(String[] args) throws Exception {
// Initialize Text File's Load options
TxtLoadOptions oTxtLoadOptions = new TxtLoadOptions(LoadFormat.CSV);
// Specify the separatot character
oTxtLoadOptions.setSeparator(',');
// Specify the encoding scheme
oTxtLoadOptions.setEncoding(Encoding.getUTF8());
// Set the flag to true for converting datetime data
oTxtLoadOptions.setConvertDateTimeData(true);
// Set the preferred parsers
oTxtLoadOptions.setPreferredParsers(new ICustomParser[] { new TextParser(), new DateParser() });
// Initialize the workbook object by passing CSV file and text load options
Workbook oExcelWorkBook = new Workbook(sourceDir + "samplePreferredParser.csv", oTxtLoadOptions);
// Get the first cell
Cell oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("A1");
// Display type of value
System.out.println("A1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue());
// Get the second cell
oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("B1");
// Display type of value
System.out.println("B1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue());
// Save the workbook to disc
oExcelWorkBook.save(outputDir + "outputsamplePreferredParser.xlsx");
System.out.println("OpeningCSVFilesWithPreferredParser executed successfully.\r\n");
}
private static String getCellType(int type){
if(type == CellValueType.IS_STRING){
return "String";
} else if(type == CellValueType.IS_NUMERIC){
return "Numeric";
} else if(type == CellValueType.IS_BOOL){
return "Bool";
} else if(type == CellValueType.IS_DATE_TIME){
return "Date";
} else if(type == CellValueType.IS_NULL){
return "Null";
} else if(type == CellValueType.IS_ERROR){
return "Error";
} else{
return "Unknown";
}
}

打开 TSV(制表符分隔)文件

制表符分隔文件包含电子表格数据但不包含任何格式。数据以行和列的形式排列,就像表格和电子表格一样。简单来说,制表符分隔的文件是一种特殊的纯文本文件,在文本中的每一列之间都有一个制表符。

要打开制表符分隔的文件,开发人员应使用 LoadOptions 类并选择在 LoadFormat 枚举中预定义的 TSV 值。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningTabDelimitedFiles.class) + "loading_saving/";
// Creating and TAB_DELIMITED LoadOptions object
LoadOptions loadOptions5 = new LoadOptions(LoadFormat.TSV);
// Creating an Workbook object with Tab Delimited text file path and the
// loadOptions object
Workbook workbook7 = new Workbook(dataDir + "Book1TabDelimited.txt", loadOptions5);
// Print message
System.out.println("Tab Delimited workbook has been opened successfully.");

打开密码加密的 Excel 文件

我们知道可以使用Microsoft Excel创建加密的Excel文件。要打开这种加密文件,开发人员应调用特殊的重载LoadOptions方法,并在FileFormatType枚举中选择预定义的DEFAULT值。该方法还将接受加密文件的密码,如下面的示例所示。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(OpeningEncryptedExcelFiles.class) + "loading_saving/";
// Opening Encrypted Excel Files
// Creating and EXCEL_97_TO_2003 LoadOptions object
LoadOptions loadOptions6 = new LoadOptions(LoadFormat.EXCEL_97_TO_2003);
// Setting the password for the encrypted Excel file
loadOptions6.setPassword("1234");
// Creating an Workbook object with file path and the loadOptions object
Workbook workbook8 = new Workbook(dataDir + "encryptedBook.xls", loadOptions6);
// Print message
System.out.println("Encrypted workbook has been opened successfully.");

Aspose.Cells还支持打开受密码保护的MS Excel 2013文件。

打开SXC文件

StarOffice Calc类似于Microsoft Excel,并支持公式、图表、函数和宏。使用此软件创建的电子表格以SXC扩展名保存。SXC文件也用于OpenOffice.org Calc电子表格文件。Aspose.Cells可以读取SXC文件,如以下代码示例所示。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the source directory.
String sourceDir = Utils.Get_SourceDirectory();
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.SXC);
// Create a Workbook object and opening the file from its path
Workbook workbook = new Workbook(sourceDir + "SampleSXC.sxc", loadOptions);
// Using the Sheet 1 in Workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Accessing a cell using its name
Cell cell = worksheet.getCells().get("C3");
System.out.println("Cell Name: " + cell.getName() + " Value: " + cell.getStringValue());

打开FODS文件

FODS 文件是以 OpenDocument XML 格式保存的未压缩电子表格。Aspose.Cells 可以读取 FODS 文件,如以下代码示例所示。

示例

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the source directory.
String sourceDir = Utils.Get_SourceDirectory();
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.FODS);
// Create a Workbook object and opening the file from its path
Workbook workbook = new Workbook(sourceDir + "SampleFods.fods", loadOptions);
// Print message
System.out.println("FODS file opened successfully!");

高级主题