日期:2014-05-16  浏览次数:20367 次

导出excel
下面代码怎么 转换成Excel文档流,并输出到客户端
实现下载啊?

  /// <summary>
    /// 将DataTable数据导出到Excel文件中(xlsx)
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="file"></param>
    public static void TableToExcelForXLSX(DataTable dt, string file)
    {
        XSSFWorkbook xssfworkbook = new XSSFWorkbook();
        ISheet sheet = xssfworkbook.CreateSheet("Test");

        //表头
        IRow row = sheet.CreateRow(0);
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            ICell cell = row.CreateCell(i);
            cell.SetCellValue(dt.Columns[i].ColumnName);
        }

        //数据
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            IRow row1 = sheet.CreateRow(i + 1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ICell cell = row1.CreateCell(j);
                cell.SetCellValue(dt.Rows[i][j].ToString());
            }
        }

        //转为字节数组
        MemoryStream stream = new MemoryStream();
        xssfworkbook.Write(stream);
        var buf = stream.ToArray();

        //保存为Excel文件
        using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
        {
            fs.Write(buf, 0, buf.Length);
            fs.Flush();
        }


    }

------解决方案--------------------
这是生成xls的代码...

生成了之后 直接

<a href='123.xls'>下载</a>


或者

 public static void downloadfile(string s_fileName)
    {
        HttpContext.Current.Response.ContentType&n