Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c# - how can we give header and title to excel sheet in asp.net in following function

my function which i want to format is as follows

private void GenerateXLSXFile(DataTable tbl)
{
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorkSheet excelWorksheet = excelPackage.Workbook.Worksheets.Add("DemoPage");
excelWorksheet.Cells("A1").LoadFromDataTable(tbl, true);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
MemoryStream stream = new MemoryStream(excelPackage.GetAsByteArray());
Response.OutputStream.Write(stream.ToArray(), 0, stream.ToArray().Length);
Response.Flush();
Response.Close();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Take a temp grid and then if you using datatable use that or use datas as follows...

DataSet ds = ViewState["Data"] as DataSet;
                DataView sortedView = (ds.Tables[0]).DefaultView;
                //DataTable dt = ViewState["Data"].ToString();

                //Create a dummy GridView
                GridView GridView1 = new GridView();
                GridView1.AllowPaging = false;
                GridView1.DataSource = sortedView;
                GridView1.DataBind();
                GridView1.Caption = "ABCD"; //// allows you to give caption to excel sheet
                Response.Clear();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment;filename=RM.xls");
                Response.Charset = "";
                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.Caption = "RM Master";
                GridView1.RenderControl(hw);
                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...