C# .net 将数据导出excel字段字符长度超出excel单元格限制时使用CSV文件导出

2021-06-26 16:05

阅读:529

标签:while   row   get   datatable   header   cvs   方便   ext   for   

datatable导出成CSV文件,并下载

public void ExportToCSV(DataTable dt, string fileName)
        {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            for (i = 0; i 1; i++)
            {
                if (i > 0) { sb.Append(","); }
                sb.Append(dt.Columns[i].ColumnName);
            }
            sb.Append("\n");
            foreach (DataRow dr in dt.Rows)
            {
                for (i = 0; i 1; i++)
                {
                    if (i > 0) { sb.Append(","); }
                    sb.Append(dr[i].ToString().Replace(",",""));
                }
                sb.Append("\n");
            }

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
            byte[] outBuffer = new byte[buffer.Length + 3];
            outBuffer[0] = (byte)0xEF;
            outBuffer[1] = (byte)0xBB;
            outBuffer[2] = (byte)0xBF;
            Array.Copy(buffer, 0, outBuffer, 3, buffer.Length);

            System.Web.HttpResponse rs = System.Web.HttpContext.Current.Response;
            rs.ContentEncoding = System.Text.Encoding.UTF8;
            rs.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            rs.ContentType = "application/ms-excel";
            rs.Write(Encoding.UTF8.GetString(outBuffer));
            rs.Flush();
            rs.End();
        }

 

CSV文件上传导入到datatable中

public DataTable GetdataFromCVS(Stream stream)

        {

            DataTable dt = new DataTable();

            StreamReader sr = new StreamReader(stream);

            string strTitle = sr.ReadLine();

            string[] strColumTitle = strTitle.Split(,);   //CVS 文件默认以逗号隔开

            for (int i = 0; i )

            {

                dt.Columns.Add(strColumTitle[i]);

            }

            while (!sr.EndOfStream)

            {

                string strTest = sr.ReadLine();

                string[] strTestAttribute = strTest.Split(,);

                DataRow dr = dt.NewRow();

                for (int i = 0; i )

                {

                    dr[strColumTitle[i]] = strTestAttribute[i];

                }

                dt.Rows.Add(dr);

            }

            return dt;

        }

 

非常方便好用数据存储量大,字段长度不限制格式简单方便

C# .net 将数据导出excel字段字符长度超出excel单元格限制时使用CSV文件导出

标签:while   row   get   datatable   header   cvs   方便   ext   for   

原文地址:https://www.cnblogs.com/budongjiuchaziliao/p/10102077.html


评论


亲,登录后才可以留言!