Write Excel files C # way

Due to frequent statistics database should import Excel files at work, perform disk IO operations, so here recorded.

First create the default folder, and returns the folder path.

 Private  static  String CPATH ( String path) 
        { 
            var index = path.LastIndexOf ( " / " );
             var TEMP path.Substring = ( 0 , index);
             IF (! Directory.Exists (TEMP)) // if there is no created file folders                                
                Directory.CreateDirectory (the TEMP); // create the folder     
            return path; 

        }

data input.

   using (var s = new System.IO.StreamWriter(CPath("./测试.csv"), true, Encoding.GetEncoding("GB2312"), 30))
                {
                    s.WriteLine($"{"列1"},{"列2"}");
                    foreach (var item in list)
                    {
                        s.WriteLine($"{item.Column},{item.Column1}");
                    }
                }

In addition, we often want to export data in WebAPI project, where also recorded in this way.

/// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/test")]
        public HttpResponseMessage TestExport()
        {
            var csv = new StringBuilder();
            csv.AppendLine($"{"列1"},{"列2"}");
            foreach (var item in list)
            {
                csv.AppendLine($"{item.Column},{item.Column1}");
            }

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            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;
        }

Of course, there are many ways to export, this is just one of the more simple kind.

 

Guess you like

Origin www.cnblogs.com/xiongtaotao/p/11606813.html