using System.Collections.Generic;
using System.Web;
using System.Data;
namespace ZOA
{
public class ExportExcel
{
public ExportExcel()
{
//
//TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
}
public void ToExcel(DataTable p_Table, HttpResponse p_Response, string p_Title)
{
int _CountR = p_Table.Rows.Count;//行數(shù)
int _CountC = p_Table.Columns.Count;//列數(shù)
p_Response.Clear();
p_Response.Buffer = true;
//設(shè)置Http的頭信息,編碼格式
p_Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(p_Title) + ".xls");
p_Response.ContentType = "application/ms-excel";
//設(shè)置編碼
p_Response.Charset = "GB2312";
p_Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//寫表頭
for (int i = 0; i < _CountC; i++)
{
p_Response.Write(p_Table.Columns[i].ColumnName + "\t");
}
p_Response.Write("\n");
//寫表內(nèi)容
for (int RowNo = 0; RowNo <= _CountR - 1; RowNo++)
{
string RowContent = "";
string _Content = string.Empty;
for (int CloumnNo = 0; CloumnNo <= _CountC - 1; CloumnNo++)
{
_Content = Convert.ToString(p_Table.Rows[RowNo][CloumnNo]);
if (_Content == "1900-1-1 0:00:00")
{
_Content = "";
}
if (_Content.Contains("\n") == true)
{
_Content = _Content.Replace("\n", "");
}
if (_Content.Contains("\r") == true)
{
_Content = _Content.Replace("\r", "");
}
if (_Content.Contains("\t") == true)
{
_Content = _Content.Replace("\t", "");
}
RowContent += _Content + " \t";
}
RowContent += "\n";
p_Response.Write(RowContent);
}
p_Response.End();
}
}
}
這是一個(gè)類,調(diào)用方法如下:
//導(dǎo)出數(shù)據(jù)
protected void BExportData_Click(object sender, EventArgs e)
{
ExportExcel ee = new ExportExcel();
DataTable dt = QueryMain();
//更改列名
dt.Columns["workid"].ColumnName = "編號";
dt.Columns["userid"].ColumnName = "工號";
dt.Columns["username"].ColumnName = "姓名";
dt.Columns["dept"].ColumnName = "部門";
dt.Columns["position"].ColumnName = "職位";
ee.ToExcel(dt, Response, "Report");
}