Converti CSV, TSV e TXT in Excel

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à.

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

Argomenti avanzati