I want to return a csv file to a website from an object list.
The process starts with retrieving json data from a database, convert it to a list of objects and print it to a csv file. I currently have no idea to how I should return the file, currently I save it to my own hdd (just to make sure it works like I wanted it to).
Class for the function to write the csv:
public void WriteCSV<T>(IEnumerable<T> items, string path)
{
Type itemType = typeof(T);
var props = itemType.GetProperties(BindingFlags.Public |
BindingFlags.Instance)
.OrderBy(p => p.Name);
using (var writer = new StreamWriter(path))
{
writer.WriteLine("sep=,");
writer.WriteLine(string.Join(", ", props.Select(p => p.Name)));
foreach (var item in items)
{
writer.WriteLine(string.Join(", ", props.Select(p =>
p.GetValue(item, null))));
}
}
}
Class to call the method and runt the file to the user:
public List<jsonObj> dataList = new List<jsonObj>();
[HttpGet]
[Route("api/csv/{id}")]
public IActionResult getCsv(int id)
{
var client = new HttpClient();
var json = client.GetStringAsync("http://localhost:52716/api/csv/data/" + id).Result;
dataList = JsonConvert.DeserializeObject<List<jsonObj>>(json);
WriteCSV(dataList, @"C:\Users\****\Desktop\min.csv");
return Ok();
//return File(csv, "text /csv", "results.csv");
}