Öffnen von Dateien mit verschiedenen Formaten

Einfache Möglichkeiten, Excel-Dateien zu öffnen

Öffnen durch Pfad

Um eine Microsoft Excel-Datei unter Verwendung des Dateipfads zu öffnen, übergeben Sie den Pfad der Datei als Parameter beim Erstellen der Instanz der Klasse Workbook. Der folgende Beispielcode zeigt das Öffnen einer Excel-Datei unter Verwendung des Dateipfads.

Beispiel

// 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.");

Öffnen durch Stream

Manchmal wird die Excel-Datei, die Sie öffnen möchten, als Stream gespeichert. In diesem Fall übergeben Sie ähnlich wie beim Öffnen einer Datei unter Verwendung des Dateipfads den Stream als Parameter beim Instanziieren der Klasse Workbook. Der folgende Beispielcode zeigt das Öffnen einer Excel-Datei unter Verwendung eines Streams.

Beispiel

// 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.");

Öffnen von Dateien verschiedener Microsoft Excel-Versionen

Der Benutzer kann die Klasse LoadOptions verwenden, um das Format der Excel-Datei unter Verwendung der Enumerationswert LoadFormat festzulegen.

Die LoadFormat-Enumeration enthält viele vordefinierte Dateiformate, von denen einige unten aufgeführt sind.

Format-Typen Beschreibung
Csv Stellt eine CSV-Datei dar
Excel97To2003 Stellt eine Excel 97 - 2003-Datei dar
Xlsx Stellt eine Excel 2007/2010/2013/2016/2019 und Office 365 XLSX-Datei dar
Xlsm Stellt eine Excel 2007/2010/2013/2016/2019 und Office 365 XLSM-Datei dar
Xltx Stellt eine Excel 2007/2010/2013/2016/2019 und Office 365-Vorlage XLTX-Datei dar
Xltm Stellt eine Excel 2007/2010/2013/2016/2019 und Office 365 makrofähige XLTM-Datei dar
Xlsb Stellt eine Excel 2007/2010/2013/2016/2019 und Office 365 binäre XLSB-Datei dar
SpreadsheetML Stellt eine SpreadsheetML-Datei dar
Tsv Stellt eine Tabstoppwerte-Datei dar
TabDelimited Stellt eine tabulatorgetrennte Textdatei dar
Ods Stellt eine ODS-Datei dar
Html Stellt eine HTML-Datei dar
Mhtml Stellt eine MHTML-Datei dar

Öffnen von Microsoft Excel 95/5.0-Dateien

Um Microsoft Excel 95-Dateien zu öffnen, instanziieren Sie die Instanz von Workbook mit dem Pfad oder Stream der Vorlagendatei. Die Beispieldatei zur Codeprüfung kann von folgendem Link heruntergeladen werden:

Excel95_5.0.xls

Beispiel

// 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");

Öffnen von Microsoft Excel 97 oder späteren Versionen XLS-Dateien

Um XLS-Dateien von Microsoft Excel XLS 97 oder späteren Versionen zu öffnen, instanziieren Sie die Instanz von Workbook mit dem Pfad oder Stream der Vorlagendatei. Oder verwenden Sie die LoadOptions-Methode und wählen Sie den EXCEL_97_TO_2003-Wert in der Enumeration LoadFormat.

Beispiel

// 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.");

Öffnen von Microsoft Excel 2007 oder späteren Versionen XLSX-Dateien

Um XLSX-Dateien von Microsoft Excel 2007 oder späteren Versionen zu öffnen, instanziieren Sie die Instanz von Workbook mit dem Pfad oder Stream der Vorlagendatei. Oder verwenden Sie die Klasse LoadOptions und wählen Sie den XLSX-Wert in der Enumeration LoadFormat.

Beispiel

// 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.");

Öffnen von Dateien mit verschiedenen Formaten

Mit Aspose.Cells können Entwickler Tabellendateien mit verschiedenen Formaten wie SpreadsheetML, CSV, Tabstopp-getrennte Dateien öffnen. Um solche Dateien zu öffnen, können Entwickler die gleiche Methodik wie für das Öffnen von Dateien verschiedener Microsoft Excel-Versionen verwenden.

Öffnen von SpreadsheetML-Dateien

SpreadsheetML-Dateien sind die XML-Repräsentationen Ihrer Tabellenkalkulationen, einschließlich aller Informationen über die Tabellenkalkulation wie Formatierung, Formeln usw. Seit Microsoft Excel XP wurde eine XML-Exportoption zu Microsoft Excel hinzugefügt, die Ihre Tabellenkalkulationen in SpreadsheetML-Dateien exportiert.

Um SpreadsheetML-Dateien zu öffnen, verwenden Sie die Klasse LoadOptions und wählen Sie den SPREADSHEET_ML-Wert in der Enumeration LoadFormat.

Beispiel

// 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.");

Öffnen von CSV-Dateien

CSV-Dateien (Comma-Separated Values) enthalten Datensätze, deren Werte durch Kommas getrennt oder voneinander abgegrenzt sind. In CSV-Dateien werden Daten in einem tabellarischen Format gespeichert, bei dem die Felder durch das Komma getrennt und durch das Anführungszeichen gekennzeichnet sind. Enthält der Wert eines Feldes ein Anführungszeichen, wird es durch ein Paar doppelter Anführungszeichen escapet. Sie können auch Microsoft Excel verwenden, um Ihre Tabellendaten in eine CSV-Datei zu exportieren.

Zum Öffnen von CSV-Dateien verwenden Sie die Klasse LoadOptions und wählen den Wert CSV aus, der in der Aufzählung LoadFormat vordefiniert ist.

Beispiel

// 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.");

Öffnen von CSV-Dateien und Ersetzen ungültiger Zeichen

In Excel werden beim Öffnen einer CSV-Datei mit Sonderzeichen die Zeichen automatisch ersetzt. Das gleiche geschieht auch durch die Aspose.Cells-API, wie im folgenden Codebeispiel demonstriert.

Beispiel

// 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!");

Öffnen von CSV-Dateien mithilfe des bevorzugten Parsers

Es ist nicht immer notwendig, die Standardparser-Einstellungen für das Öffnen der CSV-Dateien zu verwenden. Manchmal erzeugt das Importieren einer CSV-Datei nicht den erwarteten Output, z. B. ist das Datumsformat nicht wie erwartet oder leere Felder werden unterschiedlich behandelt. Hierfür steht die Klasse TxtLoadOptions.PreferredParsers zur Verfügung, um den bevorzugten Parser zum Parsen verschiedener Datentypen entsprechend den Anforderungen bereitzustellen. Der folgende Beispielcode zeigt die Verwendung des bevorzugten Parsers.  

Die Quell- und Ausgabedateien können von den folgenden Links heruntergeladen werden, um diese Funktion zu testen.

samplePreferredParser.csv

outputsamplePreferredParser.xlsx

Beispiel

// 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";
}
}

Öffnen von TSV (Tab Limited) Dateien

Tab-stufige Dateien enthalten Tabellendaten, jedoch ohne jegliche Formatierung. Daten sind in Zeilen und Spalten angeordnet, ähnlich wie in Tabellen und Tabellenkalkulationen. Kurz gesagt ist eine tabstufige Datei eine bestimmte Art von Klartextdatei mit einem Tabulator zwischen jeder Spalte in dem Text.

Zum Öffnen von tabstoppgetrennten Dateien sollten Entwickler die Klasse LoadOptions verwenden und den Wert TSV auswählen, der in der Aufzählung LoadFormat vordefiniert ist.

Beispiel

// 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.");

Öffnen verschlüsselter Excel-Dateien

Wir wissen, dass es möglich ist, verschlüsselte Excel-Dateien mit Microsoft Excel zu erstellen. Um solche verschlüsselten Dateien zu öffnen, sollten Entwickler eine spezielle überladene LoadOptions-Methode aufrufen und den DEFAULT-Wert auswählen, der in der Aufzählung FileFormatType vordefiniert ist. Diese Methode würde auch das Passwort für die verschlüsselte Datei wie im folgenden Beispiel zeigen.

Beispiel

// 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 unterstützt auch das Öffnen von passwortgeschützten MS Excel 2013-Dateien.

Öffnen von SXC Dateien

StarOffice Calc ist ähnlich wie Microsoft Excel und unterstützt Formeln, Diagramme, Funktionen und Makros. Die mit dieser Software erstellten Tabellenkalkulationen werden mit der SXC-Erweiterung gespeichert. Die SXC-Datei wird auch für OpenOffice.org Calc-Tabellenkalkulationsdateien verwendet. Aspose.Cells kann SXC-Dateien lesen, wie im folgenden Codebeispiel demonstriert wird.

Beispiel

// 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());

Öffnen von FODS Dateien

Eine FODS-Datei ist eine Tabellendatei, die im OpenDocument-XML ohne Kompression gespeichert ist. Aspose.Cells kann FODS-Dateien lesen, wie im folgenden Codesample demonstriert.

Beispiel

// 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!");

Erweiterte Themen