Convertir CSV, TSV et TXT en Excel
Ouverture des fichiers CSV
Les fichiers de valeurs séparées par des virgules (CSV) contiennent des enregistrements dont les valeurs sont délimitées ou séparées par des virgules. Dans les fichiers CSV, les données sont stockées dans un format tabulaire qui a des champs séparés par le caractère virgule et mis entre guillemets par le caractère double quote. Si la valeur d’un champ contient un double guillemet, elle est échappée avec une paire de double guillemets. Vous pouvez également utiliser Microsoft Excel pour exporter les données de votre feuille de calcul vers un fichier CSV.
Pour ouvrir des fichiers CSV, utilisez la classe LoadOptions et sélectionnez la valeur CSV, prédéfinie dans l’énumération LoadFormat.
Exemple
// 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."); |
Ouverture des fichiers CSV et remplacement des caractères invalides
Dans Excel, lorsqu’un fichier CSV avec des caractères spéciaux est ouvert, les caractères sont automatiquement remplacés. Il en va de même pour l’API Aspose.Cells qui est démontrée dans l’exemple de code ci-dessous.
Exemple
// 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!"); |
Ouverture des fichiers CSV en utilisant un analyseur préféré
Ce n’est pas toujours nécessaire d’utiliser les paramètres de l’analyseur par défaut pour ouvrir les fichiers CSV. Parfois, l’importation d’un fichier CSV ne crée pas la sortie attendue, comme le format de date n’est pas tel qu’attendu ou les champs vides sont gérés différemment. Dans ce but, TxtLoadOptions.PreferredParsers est disponible pour fournir son propre analyseur préféré pour analyser différents types de données selon les besoins. Le code d’exemple suivant illustre l’utilisation de l’analyseur préféré.
Le fichier source d’échantillon et les fichiers de sortie peuvent être téléchargés aux liens suivants pour tester cette fonctionnalité.
outputsamplePreferredParser.xlsx
Exemple
// 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"; | |
} | |
} |
Ouverture des fichiers TSV (Séparé par des tabulations)
Les fichiers tabulés contiennent des données de feuilles de calcul mais sans mise en forme. Les données sont disposées en lignes et colonnes comme des tableaux et des feuilles de calcul. Bref, un fichier tabulé est un type spécial de fichier texte simple avec une tabulation entre chaque colonne dans le texte.
Pour ouvrir des fichiers tabulés, les développeurs doivent utiliser la classe LoadOptions et sélectionner la valeur TSV, prédéfinie dans l’énumération LoadFormat.
Exemple
// 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."); |