zoukankan      html  css  js  c++  java
  • asp.net 将数据导成Excel文件

    思路:和word红头文件一样,采用xml格式的模板文件,再替换模板中设置好的标签就可以了.
    参考网址:http://www.cnblogs.com/tzy080112/p/3413938.html
    public partial class ImportExcel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnImport_Click(object sender, EventArgs e) { byte[] bytes = GetData(Server.MapPath(@"ExcelTemplateTpExcel.xml"), ""); //实现下载 Response.AddHeader("Content-Type", "application/octet-stream"); Response.Buffer = true; Response.ContentType = "*/*"; Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("导出的文件.xls", System.Text.Encoding.UTF8)); Response.AddHeader("Content-Length", bytes.Length.ToString()); Response.BinaryWrite(bytes); Response.End(); } public List<MyUser> LoadUser() { List<MyUser> li = new List<MyUser>(); MyUser u1 = new MyUser(); u1.Name = "snow"; u1.StaffNo = "1234"; MyUser u2 = new MyUser(); u2.Name = "张山"; u2.StaffNo = "200000"; li.Add(u1); li.Add(u2); return li; } public byte[] GetData(string path, string tempName) { //实例化内存流 MemoryStream fileStream = new MemoryStream(); //写文件流 StreamWriter fileWriter = new StreamWriter(fileStream); //读文件流 StreamReader fileReader = new StreamReader(path, System.Text.Encoding.UTF8); //读取整个文件的内容 string tempStr = fileReader.ReadToEnd(); //得到要导出的信息 //DataTable dt = airport.GetDataView(); List<MyUser> li = this.LoadUser(); //定义变量获取表的数据行数 int rows = 0; //定义StringBuilder变量来存储字符串 StringBuilder sb = new StringBuilder(); //判断表是否有数据 if (li.Count > 0) { //给变量赋值 rows = li.Count; int num = rows + 1;//此处1表示模板中表头的行数,且默认为1,可自行增加表头并定义 if (tempStr.IndexOf("+#RowCount#+") > 0) { tempStr = tempStr.Replace("+#RowCount#+", "" + num + ""); } //开始循环生成标准字符串 for (int i = 0; i < rows; i++) { sb.Append("<Row> " + "<Cell><Data ss:Type="String">" + li[i].Name + "</Data></Cell> " + "<Cell><Data ss:Type="String">" + li[i].StaffNo + "</Data></Cell> " + "</Row> "); } if (tempStr.IndexOf("+#TableData#+") > 0) { tempStr = tempStr.Replace("+#TableData#+", sb.ToString()); } } fileWriter.WriteLine(tempStr); fileWriter.Flush(); byte[] bytes = fileStream.ToArray(); fileStream.Close(); fileWriter.Close(); fileReader.Close(); return bytes; } } public class MyUser { public string Name { get; set; } public string StaffNo { get; set; } }
  • 相关阅读:
    hdu3499---玄学的分层图
    选择合适的最短路--hdu3499
    次小生成树
    poj-1511
    2018SDIBT_国庆个人第六场
    2018SDIBT_国庆个人第五场
    2018SDIBT_国庆个人第四场
    2018SDIBT_国庆个人第三场
    2018SDIBT_国庆个人第二场
    java项目中异常处理情况
  • 原文地址:https://www.cnblogs.com/sportdog/p/3428770.html
Copyright © 2011-2022 走看看