Apertura di file con formati diversi

Semplici modi per aprire i file Excel

Apertura attraverso il percorso

Per aprire un file Excel Microsoft utilizzando il percorso del file, passare il percorso del file come parametro durante la creazione dell’istanza del**Cartella di lavoro**classe. Il codice di esempio seguente illustra l’apertura di un file di Excel utilizzando il percorso del file.

Esempio

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

Apertura tramite Stream

volte, il file Excel che desideri aprire viene archiviato come flusso. In tal caso, analogamente all’apertura di un file utilizzando il percorso del file, passare lo stream come parametro durante l’istanziazione del file**Cartella di lavoro** classe. Il codice di esempio seguente illustra l’apertura di un file Excel tramite stream.

Esempio

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

Apertura di file di diverse versioni di Excel Microsoft

L’utente può utilizzare il**LoadOptions** class per specificare il formato del file Excel utilizzando l'**Carica formato**enumerazione.

Il**Carica formato**L’enumerazione contiene molti formati di file predefiniti, alcuni dei quali sono riportati di seguito.

Tipi di formato Descrizione
Csv Rappresenta un file CSV
Excel97To2003 Rappresenta un file Excel 97 - 2003
Xlsx Rappresenta un file Excel 2007/2010/2013/2016/2019 e Office 365 XLSX
XLSM Rappresenta un file Excel 2007/2010/2013/2016/2019 e Office 365 XLSM
XLTX Rappresenta un file modello XLTX di Excel 2007/2010/2013/2016/2019 e Office 365
Xltm Rappresenta un file XLTM abilitato per le macro di Excel 2007/2010/2013/2016/2019 e Office 365
Xlsb Rappresenta un file binario XLSB di Excel 2007/2010/2013/2016/2019 e Office 365
SpreadsheetML Rappresenta un file SpreadsheetML
Tsv Rappresenta un file di valori separati da tabulazioni
TabDelimited Rappresenta un file di testo delimitato da tabulazioni
Odd Rappresenta un file ODS
HTML Rappresenta un file HTML
HTML Rappresenta un file MHTML

Apertura di file Excel 95/5.0 Microsoft

Per aprire i file Excel 95 Microsoft, creare un’istanza del file**Cartella di lavoro**instance con il percorso o il flusso del file modello. Il file di esempio per testare il codice può essere scaricato dal seguente link:

Excel95_5.0.xls

Esempio

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

Apertura Microsoft Excel 97 o versioni successive XLS File

Per aprire i file XLS di Microsoft Excel XLS 97 o versioni successive, creare un’istanza del**Cartella di lavoro**instance con il percorso o il flusso del file modello. Oppure usa il**LoadOptions** metodo e selezionare il**EXCEL_97_TO_2003** valore in**Carica formato**enumerazione.

Esempio

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

Apertura Microsoft Excel 2007 o versioni successive XLSX File

Per aprire i file XLSX di Microsoft Excel 2007 o versioni successive, creare un’istanza del**Cartella di lavoro**instance con il percorso o il flusso del file modello. Oppure usa il**LoadOptions** classe e selezionare il**XLSX** valore in**Carica formato**enumerazione.

Esempio

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

Apertura di file con formati diversi

Aspose.Cells consente agli sviluppatori di aprire file di fogli di calcolo con diversi formati come SpreadsheetML, CSV, file delimitati da tabulazioni. Per aprire tali file, gli sviluppatori possono utilizzare la stessa metodologia utilizzata per aprire file di diverse versioni di Excel Microsoft.

Apertura file SpreadsheetML

file SpreadsheetML sono le rappresentazioni XML dei tuoi fogli di calcolo, comprese tutte le informazioni sul foglio di calcolo come formattazione, formule, ecc. A partire da Microsoft Excel XP, a Microsoft Excel viene aggiunta un’opzione di esportazione XML che esporta i tuoi fogli di calcolo in file SpreadsheetML.

Per aprire i file SpreadsheetML, utilizzare il file**LoadOptions** classe e selezionare il**SPREADSHEET_ML** valore in**Carica formato**enumerazione.

Esempio

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

Apertura file CSV

I file Comma Separated Values (CSV) contengono record i cui valori sono delimitati o separati da virgole. Nei file CSV, i dati vengono archiviati in un formato tabulare con campi separati dal carattere virgola e quotati dal carattere virgolette. Se il valore di un campo contiene un carattere di doppia virgoletta, viene preceduto da una coppia di caratteri di doppia virgoletta. Puoi anche utilizzare Microsoft Excel per esportare i dati del foglio di calcolo in un file CSV.

Per aprire i file CSV, utilizzare il file**LoadOptions** classe e selezionare il**CSV** valore, predefinito nel**Carica formato**enumerazione.

Esempio

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

Apertura di file CSV e sostituzione di caratteri non validi

In Excel, quando viene aperto il file CSV con caratteri speciali, i caratteri vengono sostituiti automaticamente. Lo stesso viene fatto da Aspose.Cells API che è dimostrato nell’esempio di codice fornito di seguito.

Esempio

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

Apertura dei file CSV utilizzando il parser preferito

Questo non è sempre necessario per utilizzare le impostazioni predefinite del parser per aprire i file CSV. A volte l’importazione del file CSV non crea l’output previsto come il formato della data non è come previsto o i campi vuoti vengono gestiti in modo diverso. Per questo scopo**TxtLoadOptions.PreferredParsers**è disponibile per fornire il proprio parser preferito per analizzare diversi tipi di dati secondo il requisito. Il seguente codice di esempio illustra l’utilizzo del parser preferito.

Il file sorgente di esempio e i file di output possono essere scaricati dai seguenti collegamenti per testare questa funzione.

samplePreferredParser.csv

outputsamplePreferredParser.xlsx

Esempio

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

Apertura di file TSV (delimitati da tabulazioni).

I file delimitati da tabulazioni contengono dati del foglio di calcolo ma senza alcuna formattazione. I dati sono disposti in righe e colonne come tabelle e fogli di calcolo. In breve, un file delimitato da tabulazioni è un tipo speciale di file di testo semplice con una tabulazione tra ogni colonna del testo.

Per aprire file delimitati da tabulazioni, gli sviluppatori dovrebbero utilizzare l’estensione**LoadOptions** classe e selezionare il**TSV** valore, predefinito nel**Carica formato**enumerazione.

Esempio

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

Apertura di file Excel crittografati

Sappiamo che è possibile creare file Excel crittografati utilizzando Microsoft Excel. Per aprire tali file crittografati, gli sviluppatori devono chiamare uno speciale metodo LoadOptions con overload e selezionare il valore DEFAULT, predefinito nell’enumerazione FileFormatType. Questo metodo prenderebbe anche la password per il file crittografato come mostrato di seguito nell’esempio.

Esempio

// 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 supporta anche l’apertura di file MS Excel 2013 protetti da password.

Apertura file SXC

StarOffice Calc è simile a Microsoft Excel e supporta formule, grafici, funzioni e macro. I fogli di calcolo creati con questo software vengono salvati con l’estensione SXC. Il file SXC viene utilizzato anche per i file del foglio di calcolo di OpenOffice.org Calc. Aspose.Cells può leggere i file SXC come dimostrato dal seguente esempio di codice.

Esempio

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

Apertura file FODS

Il file FODS è un foglio di calcolo salvato in OpenDocument XML senza alcuna compressione. Aspose.Cells può leggere i file FODS come dimostrato dal seguente esempio di codice.

Esempio

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

Argomenti avanzati