使用ClosedXML导出Excel

来源:互联网 发布:mac升级后windows没了 编辑:程序博客网 时间:2024/05/22 02:20

一、资源:ClosedXML提供VB.NET和C#两种版本,可以在ClosedXML上下载。

            这个是开源的,网站上有源代码。

二、ClosedXML需要Visual Studio 2010,可以导出Excel 2003、2007、2010版本。

 

三、使用ClosedXML

      1、引用ClosedXml.dll和DocmentFormat.OpenXml

      2、using ClosedXML.Excel

 

例子

      

        //data        string[,] data = {{"班级","姓名","成绩"}        ,{"1班","张三","90"},{"2班","李四","90"},{"3班","王五四","90"}};


 

          

            string xlName = "xlName";            //实例一个Workbook            var xlBook = new XLWorkbook();            //实例一个worksheet            var ws = xlBook.Worksheets.Add("sheet1");            for(int i = 0; i < 4;i++)                for(int j = 0;j < 3;j++)                    ws.Cell(i+1, j+1).Value = data[i,j];            MemoryStream ms = new MemoryStream();            xlBook.SaveAs(ms);            ms.Flush();            ms.Position = 0;            byte[] oByte = null;            oByte = ms.ToArray();            HttpContext.Current.Response.Clear();            HttpContext.Current.Response.ClearHeaders();            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel.sheet.binary.macroEnabled.12";            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + xlName + ".xlsx");            HttpContext.Current.Response.BinaryWrite(oByte);            //清除缓存            HttpContext.Current.Response.Flush();            HttpContext.Current.Response.End();            //关闭缓冲区            ms.Close();


 

 

原创粉丝点击