DataTable2Excel无乱码(UTF8)

本文介绍了一个用于将DataTable数据导出到Excel的方法,该方法能够处理中文字符不出现乱码的问题,并允许自定义文件名、标题、字体样式等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class ExportToExcel
    {
        #region 成员变量声明
        private DataTable _exportData;
        private string _filename = "ExportData.xls";
        private string _title = "";
        private string _extraInfo = "";
        private string title_FontName = "Arial,sans-serif";
        private string title_FontSize = "12";   //Pt
        private bool title_FontBold = true;     //默认粗体
        private string _dateTimeFormate = "{0:d}"; //默认日期格式{0:d}
        private const string C_HTTP_HEADER_CONTENT = "Content-Disposition";
        private const string C_HTTP_ATTACHMENT = "attachment;filename=";
        private const string C_HTTP_INLINE = "inline;filename=";
        private const string C_HTTP_CONTENT_TYPE_EXCEL = "application/ms-excel";
        private const string C_HTTP_CONTENT_LENGTH = "Content-Length";
        private const string C_ERROR_NO_RESULT = "Data not found.";
        private const string C_TABLE_START = "<TABLE cellSpacing=1 cellPadding=1   border=1>";
        private const string C_TABLE_END = "</TABLE>";
        #endregion 成员变量声明
        #region 属性
        /// <summary>
        /// 获取或设置要导出的数据源
        /// </summary>
        public DataTable Datatable
        {
            get
            {
                return this._exportData;
            }
            set
            {
                this._exportData = value;
            }
        }

        /// <summary>
        /// 获取或设置导出的文件名称
        /// </summary>
        public string FileNameToExport
        {
            get
            {
                return this._filename;
            }
            set
            {
                if (value != null && value.Trim() != "")
                {
                    if (value.IndexOf(".xls") < 1)
                        this._filename = HttpUtility.UrlEncode(value + ".xls", Encoding.UTF8);
                    else
                        this._filename = HttpUtility.UrlEncode(value, Encoding.UTF8);
                }
            }
        }
        /// <summary>
        /// 获取或设置标题字体
        /// 默认宋体
        /// </summary>
        public string Title_FontName
        {
            get
            {
                return this.title_FontName;
            }
            set
            {
                this.title_FontName = value;
            }
        }
        /// <summary>
        /// 获取或设置标题字体大小
        /// 默认14pt
        /// </summary>
        public string Title_FontSize
        {
            get
            {
                return this.title_FontSize;
            }
            set
            {
                this.title_FontSize = value;
            }
        }
        /// <summary>
        /// 获取或设置标题字体是否粗体
        /// 默认为粗体
        /// </summary>
        public bool Title_FontBold
        {
            get
            {
                return this.title_FontBold;
            }
            set
            {
                this.title_FontBold = value;
            }
        }
        /// <summary>
        /// 获取或设置标题
        /// </summary>
        public string Title
        {
            get
            {
                return this._title;
            }
            set
            {
                if (value != null)
                    this._title = value;
            }
        }
        /// <summary>
        /// 获取或设置除标题外其他的额外信息
        /// </summary>
        public string ExtraInfo
        {
            get
            {
                return this._extraInfo;
            }
            set
            {
                if (value != null)
                    this._extraInfo = value;
            }
        }
        /// <summary>
        /// 获取或设置日期格式
        /// 默认{0:d}
        /// </summary>
        public string DateTimeFormate
        {
            get
            {
                return this._dateTimeFormate;
            }
            set
            {
                this._dateTimeFormate = value;
            }
        }
        #endregion 属性
        #region DataTable导入到Excel(无乱码)
        public void Export(string fileName)
        {
            if (fileName.Trim().Length > 0)
            {
                FileNameToExport = fileName;
            }
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.AddHeader(C_HTTP_HEADER_CONTENT, C_HTTP_ATTACHMENT + this._filename);
            response.ContentType = C_HTTP_CONTENT_TYPE_EXCEL;
            Encoding encoding = Encoding.UTF8;
            response.ContentEncoding = encoding;
            response.Charset = "UTF-8";
            string upLoadPath = HttpContext.Current.Server.MapPath(@"~/UploadFiles/Temp/");
            string path = upLoadPath + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(this._filename);
            System.IO.StreamWriter sw = System.IO.File.CreateText(path);
            if (Datatable != null && Datatable.Rows.Count > 0)
                writeTable(Datatable, sw);
            sw.Close();
            DownFile(response, fileName, path);
            response.End();
            response.Close();
        }
        public void Export(DataTable srcDataTable, string fileName)
        {
            if (fileName.Trim().Length > 0)
            {
                FileNameToExport = fileName;
            }
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.AddHeader(C_HTTP_HEADER_CONTENT, C_HTTP_ATTACHMENT + this._filename);
            response.ContentType = C_HTTP_CONTENT_TYPE_EXCEL;
            Encoding encoding = Encoding.UTF8;
            response.ContentEncoding = encoding;
            response.Charset = "UTF-8";
            string upLoadPath = HttpContext.Current.Server.MapPath(@"~/UploadFiles/Temp/");
            string path = upLoadPath + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(this._filename);
            System.IO.StreamWriter sw = System.IO.File.CreateText(path);
            if (srcDataTable != null && srcDataTable.Rows.Count > 0)
                writeTable(srcDataTable,sw);
            sw.Close();
            DownFile(response, fileName, path);
            response.End();
            response.Close();
        }
        private bool DownFile(System.Web.HttpResponse Response, string fileName, string path)
        {
            try
            {
                Response.ContentType = "application/octet-stream";
                //Response.ContentType = "application/vnd.ms-excel";
                Response.Buffer = true;
                Response.AppendHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=UTF-8");
                StreamReader sr = new StreamReader(path, Encoding.UTF8, true);
                int size = 20480;
                string readStr = string.Empty;
                while (!sr.EndOfStream)
                {
                    while (readStr.Length < size && !sr.EndOfStream)
                    {
                        readStr += sr.ReadLine();
                    }
                    int len = Encoding.UTF8.GetByteCount(readStr);
                    len = len + readStr.Length;
                    if (len < 1024) len = 1024;
                    byte[] buffer = new byte[len];
                    Encoding.UTF8.GetBytes(readStr, 0, readStr.Length, buffer, 0);
                    readStr = string.Empty;
                    Response.BinaryWrite(buffer);
                }
                sr.Close();
                System.IO.File.Delete(path);
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void writeTable(DataTable srcData,StreamWriter sw)
        {
            int ColumnCount = srcData.Columns.Count;
            int RowCount = srcData.Rows.Count;
            sw.WriteLine(C_TABLE_START);
            //插入标题
            //if (this._title == "")
            //    this._title = srcData.TableName;
            if (this._title != "")
            {
                sw.WriteLine("<TR><TD HEIGHT=40 colSpan=" + ColumnCount + " align=center style=/"FONT-WEIGHT: " + ((this.title_FontBold) ? Convert.ToString("bold") : Convert.ToString("normal")) + "; FONT-SIZE: " + this.title_FontSize + "pt; FONT-FAMILY: " + this.title_FontName + "/">" + _title + "</TD></TR>");
            }
            //插入额外信息
            if (this._extraInfo != "")
            {
                sw.WriteLine("<TR><TD colSpan=" + ColumnCount + ">" + _extraInfo + "</TD></TR>");
                sw.WriteLine("<BR>");
            }
            sw.WriteLine("<TR>");
            //插入列标题
            foreach (DataColumn aCol in srcData.Columns)
            {
                sw.WriteLine("<TD align=center style=/"FONT-WEIGHT: bold/">" + this.ToExcelStr(aCol.Caption) + "</TD>");
            }
            sw.WriteLine("</TR>");
            //插入明细内容
            foreach (DataRow aRow in srcData.Rows)
            {
                sw.WriteLine("<TR>");
                foreach (DataColumn aCol in srcData.Columns)
                {
                    object obj = aRow[aCol.ColumnName];
                    if (aCol.DataType.FullName == "System.String")
                        //下面一句的Style属性设置所有的数字都为字符串格式,即身份证能正常显示
                        sw.WriteLine("<TD style='vnd.ms-excel.numberformat:@'>" + ((obj == null) ? " " : this.ToExcelStr(obj.ToString())) + "</TD>");
                    else if (aCol.DataType.FullName == "System.Int32")
                        sw.WriteLine("<TD style='align:right'>" + ((obj == null) ? " " : this.ToExcelStr(obj.ToString())) + "</TD>");
                    else if (aCol.DataType.FullName == "System.DateTime")
                    {
                        sw.WriteLine("<TD style='vnd.ms-excel.numberformat:@'>" + ((obj == null) ? " " : this.ToExcelStr(string.Format(DateTimeFormate, obj))) + "</TD>");
                    }
                    else sw.WriteLine("<TD>" + ((obj == null) ? " " : this.ToExcelStr(obj.ToString())) + "</TD>");
                }
                sw.WriteLine("</TR>");
            }
            sw.WriteLine(C_TABLE_END);
        }
      
        private string ToExcelStr(string srcStr)
        {
            if (srcStr == null || srcStr == "")
                return "";
            else
            {
                string rtnStr = srcStr.Replace(Environment.NewLine, "");
                rtnStr = rtnStr.Replace(" ", " ");
                rtnStr = rtnStr.Replace("<", "<");
                rtnStr = rtnStr.Replace(">", ">");
                rtnStr = rtnStr.Replace("/n", "");
                rtnStr = rtnStr.Replace("/r", "");
                return rtnStr;
            }
        }
        #endregion
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值