Apertura dei file con formati diversi

Apertura di file con formati diversi

Aspose.Cells consente agli sviluppatori di aprire file di fogli di calcolo con formati diversi come SpreadsheetML, valori separati da virgola (CSV), valori delimitati da tabulazione o valori separati da tabulazione (TSV), file ODS. Per aprire tali file, gli sviluppatori possono utilizzare la stessa metodologia utilizzata per l’apertura di file di diverse versioni di Microsoft Excel.

Apertura dei file SpreadsheetML

I file SpreadsheetML sono rappresentazioni XML di fogli di calcolo che includono tutte le informazioni ad esse relative, come formattazione, formule, ecc. Dall’introduzione di Microsoft Excel XP, è stata aggiunta un’opzione di esportazione XML a Microsoft Excel che esporta i fogli di calcolo in file SpreadsheetML.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening SpreadsheetML Files
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions3 = new LoadOptions(LoadFormat.SpreadsheetML);
// Create a Workbook object and opening the file from its path
Workbook wbSpreadSheetML = new Workbook(dataDir + "Book3.xml", loadOptions3);
Console.WriteLine("SpreadSheetML file opened successfully!");

Apertura dei file HTML

Aspose.Cells consente l’apertura di file HTML nell’oggetto Workbook. Il file HTML dovrebbe essere orientato a Microsoft Excel, cioè MS-Excel dovrebbe essere in grado di aprirlo.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir + "Book1.html";
// Instantiate LoadOptions specified by the LoadFormat.
HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html);
// Create a Workbook object and opening the file from its path
Workbook wb = new Workbook(filePath, loadOptions);
// Save the MHT file
wb.Save(filePath + "output.xlsx");

Apertura dei file CSV

I file di valori separati da virgola (CSV) contengono record in cui i valori sono separati da virgole. I dati sono memorizzati come una tabella in cui ciascuna colonna è separata dal carattere virgola e citata dal carattere virgoletta doppia. Se un valore di campo contiene un carattere di virgoletta doppia, viene eseguito l’escape con una coppia di caratteri virgoletta doppia. È anche possibile utilizzare Microsoft Excel per esportare i dati del foglio di calcolo in CSV.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions4 = new LoadOptions(LoadFormat.Csv);
// Create a Workbook object and opening the file from its path
Workbook wbCSV = new Workbook(dataDir + "Book_CSV.csv", loadOptions4);
Console.WriteLine("CSV file opened successfully!");

Apertura dei file CSV e sostituzione dei caratteri non validi

In Excel, quando si apre un file CSV con caratteri speciali, i caratteri vengono automaticamente sostituiti. Lo stesso è fatto dall’API Aspose.Cells, come dimostrato nell’esempio di codice qui sotto.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Source directory
string sourceDir = RunExamples.Get_SourceDirectory();
var filename = sourceDir + "[20180220142533][ASPOSE_CELLS_TEST].csv";
//Load CSV file
var workbook = new Workbook(filename, new TxtLoadOptions() { Separator = ';', LoadFilter = new LoadFilter(LoadDataFilterOptions.CellData), CheckExcelRestriction = false, ConvertNumericData = false, ConvertDateTimeData = false });
Console.WriteLine(workbook.Worksheets[0].Name); // (20180220142533)(ASPOSE_CELLS_T
Console.WriteLine(workbook.Worksheets[0].Name.Length); // 31
Console.WriteLine("CSV file opened successfully!");

Utilizzo del parser preferito

Non è sempre necessario utilizzare le impostazioni predefinite del parser per aprire i file CSV. A volte l’importazione del file CSV non crea l’output atteso, ad esempio il formato data non è come previsto o i campi vuoti vengono gestiti in modo diverso. A questo scopo è disponibile TxtLoadOptions.PreferredParsers per fornire un proprio parser preferito per analizzare diversi tipi di dati secondo i requisiti. Il codice di esempio seguente 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à.

samplePreferredParser.csv

outputsamplePreferredParser.xlsx

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
class TextParser : ICustomParser
{
public object ParseObject(string value)
{
return value;
}
public string GetFormat()
{
return "";
}
}
class DateParser : ICustomParser
{
public object ParseObject(string value)
{
DateTime myDate = DateTime.ParseExact(value, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
return myDate;
}
public string GetFormat()
{
return "dd/MM/yyyy";
}
}
public static void Main()
{
// Initialize Text File's LoadFormat
LoadFormat oLoadFormat = LoadFormat.Csv;
// Initialize Text File's Load options
TxtLoadOptions oTxtLoadOptions = new TxtLoadOptions(oLoadFormat);
// Specify the separatot character
oTxtLoadOptions.Separator = Convert.ToChar(",");
// Specify the encoding scheme
oTxtLoadOptions.Encoding = System.Text.Encoding.UTF8;
// Set the flag to true for converting datetime data
oTxtLoadOptions.ConvertDateTimeData = true;
// Set the preferred parsers
oTxtLoadOptions.PreferredParsers = new ICustomParser[] { new TextParser(), new DateParser() };
// Initialize the workbook object by passing CSV file and text load options
Workbook oExcelWorkBook = new Aspose.Cells.Workbook(sourceDir + "samplePreferredParser.csv", oTxtLoadOptions);
// Get the first cell
Cell oCell = oExcelWorkBook.Worksheets[0].Cells["A1"];
// Display type of value
Console.WriteLine("A1: " + oCell.Type.ToString() + " - " + oCell.DisplayStringValue);
// Get the second cell
oCell = oExcelWorkBook.Worksheets[0].Cells["B1"];
// Display type of value
Console.WriteLine("B1: " + oCell.Type.ToString() + " - " + oCell.DisplayStringValue);
// Save the workbook to disc
oExcelWorkBook.Save(outputDir + "outputsamplePreferredParser.xlsx");
Console.WriteLine("OpeningCSVFilesWithPreferredParser executed successfully.\r\n");
}

Apertura dei file di testo con separatore personalizzato

I file di testo vengono utilizzati per contenere dati dei fogli elettronici senza formattazione. Il file è un tipo di file di testo semplice che può avere delimitatori personalizzati.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir + "Book11.csv";
// Instantiate Text File's LoadOptions
TxtLoadOptions txtLoadOptions = new TxtLoadOptions();
// Specify the separator
txtLoadOptions.Separator = Convert.ToChar(",");
// Specify the encoding type
txtLoadOptions.Encoding = System.Text.Encoding.UTF8;
// Create a Workbook object and opening the file from its path
Workbook wb = new Workbook(filePath, txtLoadOptions);
// Save file
wb.Save(dataDir+ "output.txt");

Apertura dei file delimitati da tabulazione

Il file delimitato da tabulazione (Testo) contiene dati del foglio elettronico ma senza alcuna formattazione. I dati sono disposti in righe e colonne come nelle tabelle e nei fogli elettronici. Fondamentalmente, un file delimitato da tabulazione è un tipo speciale di file di testo semplice con una tabulazione tra ogni colonna.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Opening Tab Delimited Files
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions5 = new LoadOptions(LoadFormat.TabDelimited);
// Create a Workbook object and opening the file from its path
Workbook wbTabDelimited = new Workbook(dataDir + "Book1TabDelimited.txt", loadOptions5);
Console.WriteLine("Tab delimited file opened successfully!");

Apertura dei file di valori separati da tabulazione (TSV)

Il file di valori separati da tabulazione (TSV) contiene dati del foglio elettronico ma senza alcuna formattazione. È lo stesso con il file delimitato da tabulazione dove i dati sono disposti in righe e colonne come nelle tabelle e nei fogli elettronici.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Source directory
string sourceDir = RunExamples.Get_SourceDirectory();
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.Tsv);
// Create a Workbook object and opening the file from its path
Workbook workbook = new Workbook(sourceDir + "SampleTSVFile.tsv", loadOptions);
// Using the Sheet 1 in Workbook
Worksheet worksheet = workbook.Worksheets[0];
// Accessing a cell using its name
Cell cell = worksheet.Cells["C3"];
Console.WriteLine("Cell Name: " + cell.Name + " Value: " + cell.StringValue);

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.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Source directory
string sourceDir = RunExamples.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.Worksheets[0];
// Accessing a cell using its name
Cell cell = worksheet.Cells["C3"];
Console.WriteLine("Cell Name: " + cell.Name + " Value: " + cell.StringValue);

Apertura dei file FODS

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

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
//Source directory
string sourceDir = RunExamples.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);
Console.WriteLine("FODS file opened successfully!");