zoukankan      html  css  js  c++  java
  • .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[] { ' ' }).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;
    }

    }

  • 相关阅读:
    dedecms代码研究五
    dedecms代码研究四
    判断有没有真正点击打印
    SAP中删除假脱机请求
    商品扩地点不成功
    记录一些使用的abap小程序帮助开发
    sap abap 程序 中使用 FTP . <转载>
    SM37 后台调试
    ftp上传下载| 图片上传下载
    ALV调用的几个标准函数 <转自 思微随想>
  • 原文地址:https://www.cnblogs.com/yjm8023/p/14079596.html
Copyright © 2011-2022 走看看