| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System;
- using System.Diagnostics;
- using System.Collections;
- using System.Data;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Text;
- namespace XYFDRQ.Common
- {
- /// <summary>
- /// 操作EXCEL导出数据报表的类
- /// Copyright (C) XYFDRQ
- /// </summary>
- public class DataToExcel
- {
- public DataToExcel()
- {
- }
- /// <summary>
- /// DataTable保存到Excel
- /// </summary>
- public static void SaveToExcelGB2312(DataTable p_Table, HttpResponse p_Response, string fileName)
- {
- int _CountR = p_Table.Rows.Count;//行数
- int _CountC = p_Table.Columns.Count;//列数
- p_Response.Clear();
- p_Response.Buffer = true;
- //设置编码
- p_Response.Charset = "GB2312";
- p_Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
- p_Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
- p_Response.ContentType = "application/ms-excel";
- //写表头
- for (int i = 0; i < _CountC; i++)
- {
- p_Response.Write(p_Table.Columns[i].ColumnName + "\t");
- }
- p_Response.Write("\n");
- //写表内容
- for (int RowNo = 0; RowNo <= _CountR - 1; RowNo++)
- {
- string RowContent = "";
- for (int CloumnNo = 0; CloumnNo <= _CountC - 1; CloumnNo++)
- {
- RowContent += Convert.ToString(p_Table.Rows[RowNo][CloumnNo]).Replace("\t", "").Replace("\r", "").Replace("\n", "").Replace("\"", "") + "\t";
- }
- RowContent += "\n";
- p_Response.Write(RowContent);
- }
- p_Response.End();
- }
- /// <summary>
- /// DataTable保存到Excel
- /// </summary>
- /// <param name="p_Table"></param>
- /// <param name="p_Response"></param>
- public static void SaveToExcelUtf8(DataTable p_Table, HttpResponse p_Response, string fileName)
- {
- int _CountR = p_Table.Rows.Count;//行数
- int _CountC = p_Table.Columns.Count;//列数
- p_Response.Clear();
- p_Response.Buffer = true;
- p_Response.Charset = "UTF-8";
- p_Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
- p_Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlDecode(fileName, Encoding.UTF8).ToString());
- p_Response.ContentType = "application/ms-excel";
- //写表头
- for (int i = 0; i < _CountC; i++)
- {
- p_Response.Write(p_Table.Columns[i].ColumnName + "\t");
- }
- p_Response.Write("\n");
- //写表内容
- for (int RowNo = 0; RowNo <= _CountR - 1; RowNo++)
- {
- string RowContent = "";
- for (int CloumnNo = 0; CloumnNo <= _CountC - 1; CloumnNo++)
- {
- RowContent += Convert.ToString(p_Table.Rows[RowNo][CloumnNo]) + "\t";
- }
- RowContent += "\n";
- p_Response.Write(RowContent);
- }
- p_Response.End();
- }
- }
- }
|