如何将sql表导出到Excel而不会丢失您的格式?

时间:2015-10-01 11:26:36

标签: asp.net export-to-excel

我想导出sql表来excel文件。 我的代码:

public void ExportToExcel(string strQuery)
{
    //Get the data from database into datatable
    OleDbCommand cmd = new OleDbCommand(strQuery);
    DataTable dt = GetData(cmd);

    //Create a dummy GridView
    GridView GridView1 = new GridView();
    GridView1.AllowPaging = false;
    GridView1.DataSource = dt;
    GridView1.DataBind();

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);

    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        //Apply text style to each Row
        GridView1.Rows[i].Attributes.Add("class", "textmode");
    }
    GridView1.RenderControl(hw);

    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    HttpContext.Current.Response.Write(style);
    HttpContext.Current.Response.Output.Write(sw.ToString());
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();
}

和aspx页面的按钮:

protected void ExportToExcel(object sender, EventArgs e)
{
    ExportClass Exc = new ExportClass();
    string wherestr = null;
    if ((StartTBX.Text.Length > 0) && (EndTBX.Text.Length > 0)) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And (CreateDate >='{0}' And CreateDate <='{1}')", StartTBX.Text, EndTBX.Text); }
    else if (StartTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate >='{0}'", StartTBX.Text); }
    else if (EndTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate <='{0}'", EndTBX.Text); }
    else { wherestr = "((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin')"; }
    Exc.ExportToExcel("SELECT Users.UserID, UserName, Status, LockUser, FName + ' ' + Lname as [نام کامل] FROM Users inner join UsersInfo on Users.UserID=UsersInfo.UserID WHERE " + wherestr + " ORDER BY CreateDate DESC");
}

当我不在代码中使用日期过滤时(代码中的最后一个),一切都很好但是当我使用日期过滤时,[نامکامل]格式的内容会丢失。 [نامکامل]的内容是非英语单词。

没有日期过滤器:

enter image description here

日期过滤器:

enter image description here

请帮帮我。非常感谢。

1 个答案:

答案 0 :(得分:0)

好吧,我的问题解决了这段代码:

HttpContext.Current.Response.ContentEncoding = Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(Encoding.Unicode.GetPreamble());
最好的问候。