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 } |
DataTable2Excel无乱码(UTF8)
最新推荐文章于 2022-08-30 16:54:38 发布