Convertir un fichier CSV en JSON

Convertir CSV en JSON

Aspose.Cells prend en charge la conversion de CSV en JSON. Pour cela, l’API fournit les classes ExportRangeToJsonOptions et JsonUtility. La classe ExportRangeToJsonOptions fournit les options pour exporter la plage vers JSON. La classe ExportRangeToJsonOptions a les propriétés suivantes.

  • ExportAsString: Cela exporte la valeur de chaîne des cellules au format JSON.
  • HasHeaderRow: Indique si la plage contient une ligne d’en-tête.
  • Indent: Indique l’indentation.

La classe JsonUtility exporte le JSON en utilisant les options d’export définies avec la classe ExportRangeToJsonOptions.

Le code d’exemple suivant démontre l’utilisation des classes ExportRangeToJsonOptions et JsonUtility pour charger le fichier CSV source et afficher la sortie JSON dans la console.

Code d’exemple

// 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();
LoadOptions loadOptions = new LoadOptions(LoadFormat.Csv);
// Load CSV file
Workbook workbook = new Workbook(sourceDir + "SampleCsv.csv", loadOptions);
Cell lastCell = workbook.Worksheets[0].Cells.LastCell;
// Set JsonSaveOptions
JsonSaveOptions jsonSaveOptions = new JsonSaveOptions();
Range range = workbook.Worksheets[0].Cells.CreateRange(0, 0, lastCell.Row + 1, lastCell.Column + 1);
string data = JsonUtility.ExportRangeToJson(range, jsonSaveOptions);
// Print JSON
Console.WriteLine(data);

Sortie console

[
{
"id": 1,
"language": "Java",
"edition": "third",
"author": "Herbert Schildt",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
},
{
"id": 2,
"language": "C++",
"edition": "second",
"author": "EAAAA",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
},
{
"id": 3,
"language": ".Net",
"edition": "second",
"author": "E.Balagurusamy",
"streetAddress": 126,
"city": "San Jone",
"state": "CA",
"postalCode": 394221
}
]