Добавьте файлы проекта.
This commit is contained in:
59
SQLVision.Services/Exporters/JsonExporter.cs
Normal file
59
SQLVision.Services/Exporters/JsonExporter.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SQLVision.Core.Models;
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace SQLVision.Services.Exporters;
|
||||
|
||||
public class JsonExporter : IExportHandler
|
||||
{
|
||||
private readonly ILogger<JsonExporter> _logger;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
|
||||
public string FormatName => "JSON";
|
||||
|
||||
public JsonExporter(ILogger<JsonExporter> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||
};
|
||||
}
|
||||
|
||||
public async Task ExportAsync(DataTable data, string filePath, ExportOptions options)
|
||||
{
|
||||
var records = ConvertDataTableToList(data);
|
||||
var json = JsonSerializer.Serialize(records, _jsonOptions);
|
||||
await File.WriteAllTextAsync(filePath, json);
|
||||
|
||||
_logger.LogInformation("Exported {Rows} rows to JSON: {FilePath}", data.Rows.Count, filePath);
|
||||
}
|
||||
|
||||
public async Task<byte[]> ExportToMemoryAsync(DataTable data, ExportOptions options)
|
||||
{
|
||||
var records = ConvertDataTableToList(data);
|
||||
var json = JsonSerializer.Serialize(records, _jsonOptions);
|
||||
return System.Text.Encoding.UTF8.GetBytes(json);
|
||||
}
|
||||
|
||||
private List<Dictionary<string, object>> ConvertDataTableToList(DataTable data)
|
||||
{
|
||||
var list = new List<Dictionary<string, object>>();
|
||||
|
||||
foreach (DataRow row in data.Rows)
|
||||
{
|
||||
var dict = new Dictionary<string, object>();
|
||||
|
||||
foreach (DataColumn column in data.Columns)
|
||||
{
|
||||
dict[column.ColumnName] = row[column] ?? DBNull.Value;
|
||||
}
|
||||
|
||||
list.Add(dict);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user