C#导出GridView数据到Excel文件类实例
程序员文章站
2023-12-04 17:20:04
本文实例讲述了c#导出gridview数据到excel文件类。分享给大家供大家参考。具体如下:
这段c#代码自定义了一个封装类,用于将gridview数据导出到excel...
本文实例讲述了c#导出gridview数据到excel文件类。分享给大家供大家参考。具体如下:
这段c#代码自定义了一个封装类,用于将gridview数据导出到excel文件
using system; using system.web; using system.web.ui; using system.io; using system.web.ui.webcontrols; namespace dotnet.utilities { public class exportexcel { protected void exportdata(string strcontent, string filename) { filename = filename + datetime.now.year.tostring() + datetime.now.month.tostring() + datetime.now.day.tostring() + datetime.now.hour.tostring() + datetime.now.minute.tostring() + datetime.now.second.tostring() + datetime.now.millisecond.tostring(); httpcontext.current.response.clear(); httpcontext.current.response.charset = "gb2312"; httpcontext.current.response.contenttype = "application/ms-excel"; httpcontext.current.response.contentencoding = system.text.encoding.utf8; //this.page.enableviewstate = false; // 添加头信息,为"文件下载/另存为"对话框指定默认文件名 httpcontext.current.response.addheader("content-disposition", "attachment; filename=" + filename + ".xls"); // 把文件流发送到客户端 httpcontext.current.response.write("<html><head><meta http-equiv=content-type content=\"text/html; charset=utf-8\">"); httpcontext.current.response.write(strcontent); httpcontext.current.response.write("</body></html>"); // 停止页面的执行 //response.end(); } /// <summary> /// 导出excel /// </summary> /// <param name="obj"></param> public void exportdata(gridview obj) { try { string style = ""; if (obj.rows.count > 0) { style = @"<style> .text { mso-number-format:\@; } </script> "; } else { style = "no data."; } httpcontext.current.response.clearcontent(); datetime dt = datetime.now; string filename = dt.year.tostring() + dt.month.tostring() + dt.day.tostring() + dt.hour.tostring() + dt.minute.tostring() + dt.second.tostring(); httpcontext.current.response.addheader("content-disposition", "attachment; filename=exportdata" + filename + ".xls"); httpcontext.current.response.contenttype = "application/ms-excel"; httpcontext.current.response.charset = "gb2312"; httpcontext.current.response.contentencoding = system.text.encoding.getencoding("gb2312"); stringwriter sw = new stringwriter(); htmltextwriter htw = new htmltextwriter(sw); obj.rendercontrol(htw); httpcontext.current.response.write(style); httpcontext.current.response.write(sw.tostring()); httpcontext.current.response.end(); } catch { } } } }
希望本文所述对大家的c#程序设计有所帮助。