C# 使用微软自带控件导出excel

导出excel:使用微软默认的dll,通过点击导出按钮启用js的open方法新建出一个ashx页面将文件导出到浏览器进行下载,此处放出部分代码以大概表示出顺序,完整代码见https://www.cnblogs.com/Brambling/p/6854731.html,写得可以说是非常详细了。就是别忘了导出到浏览器下载要删除目录下的缓存文件,这个是先保存到本地再输出到浏览器下载的。

            try{
                Application excel = new Application();
                excel.Visible = false;
                Workbooks workbooks = excel.Workbooks;
                Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                Worksheet worksheet = GetWorkSheet(workbook);//自定义方法
                workbook.Saved = true;
                string path = HttpContext.Current.Server.MapPath("Export/");
                FileUtil.CreateDirectory(path);
                //设置新建文件路径及名称
                savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";
                //创建文件
                System.IO.FileStream file = new System.IO.FileStream(savePath, System.IO.FileMode.CreateNew);

                //关闭释放流,不然没办法写入数据
                file.Close();
                file.Dispose();

                //保存到指定的路径
                workbook.SaveCopyAs(savePath);

                //输出到浏览器下载
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(savePath);
                context.Response.ContentType = "application/vnd.ms-excel";
                context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", "-权限清单"));
                context.Response.WriteFile(fileInfo.FullName);
                context.Response.Flush();
               }
                finally
                {
                    FileUtil.DeleteFile(savePath);
                    context.Response.End();
                }

你可能感兴趣的:(C#)