Apertura dei file con formati diversi
Gli sviluppatori utilizzano Aspose.Cells per aprire file per scopi diversi. Ad esempio, aprire un file per recuperare dati da esso, o utilizzare un file di foglio di calcolo del designer predefinito per velocizzare il processo di sviluppo. Aspose.Cells consente agli sviluppatori di aprire diversi tipi di file di origine. Questi file di origine possono essere rapporti di Microsoft Excel, SpreadsheetML, valori separati da virgola (CSV), valori delimitati da tabulazioni o valori separati da tabulazioni (TSV). Questo articolo tratta dell’apertura di questi diversi file di origine utilizzando Aspose.Cells.
Se hai bisogno di conoscere tutti i formati di file supportati, consulta le seguenti pagine: Formati file supportati
Modi semplici per aprire file Excel
Apertura attraverso percorso
Per aprire un file di Microsoft Excel utilizzando il percorso del file, passare il percorso del file come parametro durante la creazione dell’istanza della classe Workbook. Il seguente codice di esempio mostra come aprire un file 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 flusso
A volte, il file Excel che si desidera aprire è archiviato come stream. In tal caso, simile all’apertura di un file utilizzando il percorso del file, passare lo stream come parametro durante l’istanziazione della classe Workbook. Il seguente codice di esempio dimostra l’apertura di un file Excel utilizzando lo 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 Microsoft Excel
L’utente può utilizzare la classe LoadOptions per specificare il formato del file Excel utilizzando l’enumerazione LoadFormat.
L’enumerazione LoadFormat contiene molti formati di file predefiniti alcuni dei quali sono elencati di seguito.
Tipi di formato | Descrizione |
---|---|
Csv | Rappresenta un file CSV |
Excel97To2003 | Rappresenta un file Excel 97 - 2003 |
Xlsx | Rappresenta un file XLSX Excel 2007/2010/2013/2016/2019 e Office 365 |
Xlsm | Rappresenta un file XLSM Excel 2007/2010/2013/2016/2019 e Office 365 |
Xltx | Rappresenta un file modello XLTX di Excel 2007/2010/2013/2016/2019 e Office 365 |
Xltm | Rappresenta un file XLTM macro abilitato di Excel 2007/2010/2013/2016/2019 e Office 365 |
Xlsb | Rappresenta un file XLSB binario 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 |
Ods | Rappresenta un file ODS |
Html | Rappresenta un file HTML |
Mhtml | Rappresenta un file MHTML |
Apertura di file Microsoft Excel 95/5.0
Per aprire i file Microsoft Excel 95, istanziare l’istanza Workbook con il percorso o lo stream del file di modello. Il file di esempio per testare il codice può essere scaricato dal seguente link:
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 di file XLS di Microsoft Excel 97 o versioni successive
Per aprire file XLS di Microsoft Excel XLS 97 o versioni successive, istanzia l’istanza Workbook con il percorso o lo stream del file modello. Oppure utilizza il metodo LoadOptions e seleziona il valore EXCEL_97_TO_2003 nell’enumerazione LoadFormat.
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 di file XLSX di Microsoft Excel 2007 o versioni successive
Per aprire file XLSX di Microsoft Excel 2007 o versioni successive, istanzia l’istanza Workbook con il percorso o lo stream del file modello. Oppure utilizza la classe LoadOptions e seleziona il valore XLSX nell’enumerazione LoadFormat.
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 ai programmatori di aprire file di fogli elettronici con diversi formati come SpreadsheetML, CSV, file delimitati da tabulazioni. Per aprire tali file, i programmatori possono utilizzare la stessa metodologia usata per aprire file di diverse versioni di Microsoft Excel.
Apertura dei file SpreadsheetML
I file SpreadsheetML sono le rappresentazioni XML dei fogli elettronici, includendo tutte le informazioni sul foglio elettronico come formattazione, formule, ecc. Dal Microsoft Excel XP, è stata aggiunta un’opzione di esportazione XML a Microsoft Excel che esporta i fogli elettronici in file SpreadsheetML.
Per aprire file SpreadsheetML, utilizza la classe LoadOptions e seleziona il valore SPREADSHEET_ML nell’enumerazione LoadFormat.
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 dei file CSV
I file CSV (Comma Separated Values) contengono record i cui valori sono delimitati o separati da virgole. Nei file CSV, i dati sono memorizzati in un formato tabellare che ha campi separati dal carattere virgola e racchiusi dal carattere virgolette doppie. Se il valore di un campo contiene un carattere di virgolette doppie, viene trasformato con una coppia di caratteri di virgolette doppie. È anche possibile utilizzare Microsoft Excel per esportare i dati del foglio di calcolo in un file CSV.
Per aprire file CSV, utilizza la classe LoadOptions e seleziona il valore CSV, predefinito nell’enumerazione LoadFormat.
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 dei file CSV e sostituzione dei caratteri non validi
In Excel, quando viene aperto un file CSV con caratteri speciali, i caratteri vengono automaticamente sostituiti. La stessa operazione viene eseguita dall’API Aspose.Cells che è dimostrata nell’esempio di codice riportato 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
Non sempre è necessario utilizzare le impostazioni del parser predefinito per aprire i file CSV. A volte l’importazione del file CSV non crea l’output previsto, ad esempio il formato data non corrisponde alle aspettative o i campi vuoti sono gestiti in modo diverso. A tale scopo è disponibile TxtLoadOptions.PreferredParsers per fornire un proprio parser preferito per analizzare diversi tipi di dati secondo le richieste. Il seguente esempio di codice dimostra l’uso del parser preferito.
È possibile scaricare il file di origine di esempio e i file di output dai seguenti collegamenti per testare questa funzionalità.
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 dei file TSV (delimitati da tabulazione)
I file delimitati da tabulazioni contengono dati di fogli elettronici 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 puro con una tabulazione tra ciascuna colonna nel testo.
Per aprire file delimitati da tabulazioni, i programmatori dovrebbero utilizzare la classe LoadOptions e selezionare il valore TSV, predefinito nell’enumerazione LoadFormat.
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 criptati
Sappiamo che è possibile creare file Excel criptati utilizzando Microsoft Excel. Per aprire tali file criptati, i programmatori dovrebbero chiamare un metodo sovraccaricato speciale di LoadOptions e selezionare il valore DEFAULT, predefinito nell’enumerazione FileFormatType. Questo metodo richiederà anche la password per il file criptato 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 dei file SXC
StarOffice Calc è simile a Microsoft Excel e supporta formule, grafici, funzioni e macro. I fogli elettronici creati con questo software sono salvati con l’estensione SXC. Il file SXC è anche utilizzato per i file del foglio elettronico 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 dei file FODS
Il file FODS è un foglio elettronico salvato in formato 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
- Filtra i nomi definiti durante il caricamento del foglio di lavoro
- Filtra gli oggetti durante il caricamento del foglio di lavoro o del foglio di calcolo
- Ottieni avvisi durante il caricamento del file Excel
- Mantieni i separatori per le righe vuote durante l’esportazione di fogli di calcolo in formato CSV
- Carica il libro di lavoro con il formato di carta della stampante specificato
- Apertura di file di diverse versioni di Microsoft Excel
- Ottimizzazione dell’utilizzo della memoria durante il lavoro con file grandi che contengono grandi set di dati
- Leggi i fogli di calcolo di Numbers sviluppati da Apple Inc. utilizzando Aspose.Cells
- Lettura del file CSV con codifiche multiple
- Interrompere la conversione o il caricamento utilizzando InterruptMonitor quando sta impiegando troppo tempo
- Utilizzo di API LightCells