在服务器端生成Excel文件然后从服务器下载的本地的代码

时间:2021-11-12 17:49:23

这个方法适用所有类型文件,你可以适当修改代码就行了       

 protected void Button1_Click(object sender, EventArgs e)
        {
          object     filename = Guid.NewGuid()  ;
            //生成一个新的文件名用全球唯一标识符 (GUID)来标识
            string newpath = String.Format(@"{0}\Excel\{1}.xls", Server.MapPath("."), filename );
            //调用的模板文件
            FileInfo mode = new FileInfo(Server.MapPath("3.xls"));

            Excel.Application app = new Excel.Application();

            if (app == null)
            {
                return;
            }
            //app.Application.DisplayAlerts = false;
            //app.Visible = false;

            if (mode.Exists)
            {
                Object missing = System.Reflection.Missing.Value;
                Excel.Workbook tworkbook;

             
                //调用模板
                tworkbook = app.Workbooks.Open(mode.FullName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                Excel._Worksheet tworksheet;
                tworksheet =(Excel._Worksheet ) tworkbook.Sheets [1];
                Excel.Range rng = tworksheet.get_Range("A1", Missing.Value);
                rng.Value2 = "Hello";
                rng.Interior.ColorIndex = 6; //设置Range的背景色

                //tworksheet.Cells[1, 2] = "测试";
                //tworksheet.Cells[2, 2] = "测试";
                //app.Visible = true;
                tworksheet.SaveAs(newpath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                tworkbook.Save();
                tworksheet = null;
                tworkbook = null;
               
                app.Quit();
                app.Quit();
                app = null;
                    if (newpath  != "")
            {

                string path = newpath ;

                System.IO.FileInfo file = new System.IO.FileInfo(path);

                if (file.Exists)
                {
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                    Response.AddHeader("Content-Length", file.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Filter.Close();
                    Response.WriteFile(newpath  );
                    Response.End();
                }
                else
                {
                    Response.Write("This file does not exist.");
                }
            } 
                //强制对所有代进行垃圾回收
                GC.Collect();
            }

        }