.net 导出\导入 csv文件
1导出
/// <summary>
/// 导出推广名单
/// </summary>
/// <param name="id">补贴Id</param>
/// <param name="page">页码</param>
/// <returns></returns>
[HttpGet]
[Route("api/a/subitem/exportSubApplyItem")]
public HttpResponseMessage ExportSubApplyItem(int id,int page = 1,int pagesize = 1000)
{
var res = GetSubApplyItem(id,page,pagesize); //获取数据
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
if (res.PData.Count() > 0) {
var csv = new StringBuilder();
csv.AppendLine("Id,用户名");
foreach (var item in res.PData) {
csv.AppendLine($"{item.Id},{item.Nick}");
}
response.Content = new ByteArrayContent(Encoding.GetEncoding("gbk").GetBytes(csv.ToString()));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-csv");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = string.Format(@"推广名单_{0}.csv",string.Format("{0:G}",DateTime.Now)),
};
}
return response;
}
////导入
/// <summary>
/// 导入excel
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("api/a/subitem/exportSubApplyItem")]
public WebApiResult ExportSubApplyItemInfo()
{
var filelist = HttpContext.Current.Request.Files;
var file = filelist[0];
var records = GetPayDetails(file.InputStream);得到导入的数据
}
/// <summary>
/// 导入csv SubApplyPartDTO 这里是你的对象值
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public List<SubApplyPartDTO> GetPayDetails(Stream file)
{
try {
var records = new List<SubApplyPartDTO>();
if (file != null) {
string csv = "";
using (var sr = new StreamReader(file,Encoding.GetEncoding("gbk"))) {
csv = sr.ReadToEnd();
}
foreach (var line in csv.Split(new[] { '\n' }).Skip(1)) {
if (!line.NullOrEmpty()) {
var fields = line.Trim().Split(new[] { ',' });
var record = new SubApplyPartDTO {
Id = int.Parse(fields[0].Trim()),
LogisticsNum = fields[7].Trim(),
};
records.Add(record);
}
}
}
return records;
} catch (Exception ex) {
logger.Error("导入推广名单单错误:" + JsonConvert.SerializeObject(ex));
throw;
}
}