以下是ASP.NET WebAPI导出CSV的完整攻略:
一、添加CSV文件支持
- 首先,在WebApiConfig.cs文件中注册CSV输出格式,代码如下:
public static void Register(HttpConfiguration config)
{
var csvFormatter = new CsvMediaTypeFormatter();
config.Formatters.Insert(0, csvFormatter);
//其他配置
}
- 接下来,创建一个自定义的CSV媒体格式化器。该格式化器继承自MediaTypeFormatter。
public class CsvMediaTypeFormatter : MediaTypeFormatter
{
public CsvMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
}
public override bool CanWriteType(Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return IsTypeOfIEnumerable(type);
}
private bool IsTypeOfIEnumerable(Type type)
{
return type.GetInterfaces().Any(t => t == typeof(IEnumerable));
}
public override Task WriteToStreamAsync(Type type, object value,
Stream stream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() => WriteToStream(type, value, stream));
}
private void WriteToStream(Type type, object value, Stream stream)
{
StringWriter writer = new StringWriter();
writer.WriteLine("\"" + string.Join("\",\"", type.GetProperties().Select(p => p.Name)) + "\"");
foreach (var obj in (IEnumerable<object>)value)
{
var vals = obj.GetType().GetProperties().Select(prop => new {
Value = prop.GetValue(obj, null)
}).Select(v => v.Value.ToString());
var line = string.Join(",", vals);
writer.WriteLine(line);
}
var streamWriter = new StreamWriter(stream);
streamWriter.Write(writer.ToString());
streamWriter.Flush();
}
}
二、使用CSV文件导出数据
以下是两个示例:
- 导出实体数据
[HttpGet]
[Route("api/Orders/Export")]
public HttpResponseMessage ExportData()
{
var orderQuery = db.Orders.Where(x => x.Status == OrderStatus.Shipped);
//这里省略了Order实体的具体定义
var orders = orderQuery.ToList();
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ObjectContent<List<Order>>(orders, new CsvMediaTypeFormatter());
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Orders.csv"
};
return response;
}
- 导出自定义数据
[HttpGet]
[Route("api/Customers/Export")]
public HttpResponseMessage ExportData()
{
var customerQuery = db.Customers.Where(x => x.IsVIP);
var customers = customerQuery.ToList().Select(c => new {
Name = c.Name,
Gender = c.Gender == Gender.Male ? "男" : "女",
City = c.Address.City,
Province = c.Address.Province
});
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ObjectContent<IEnumerable>(customers, new CsvMediaTypeFormatter());
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Customers.csv"
};
return response;
}
以上就是ASP.NET WebAPI导出CSV的完整攻略,具体实现还需要根据项目需求进行调整。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.NET WebAPI导出CSV - Python技术站