生成Excel 输出到浏览器

using ExcelLibrary.SpreadSheet;
using System.IO;


 private string ExportExcel(DataSet ds, ref string msg)
        {
            string path = null;
            try
            {
                System.Data.DataTable dt = ds.Tables[0];
                Workbook workbook = new Workbook();

                Worksheet worksheet = new Worksheet("表1");
                int columnsCount = dt.Columns.Count;
                for (int i =0; i < columnsCount-2; i++)
                {
                    worksheet.Cells[0, i] = new Cell(dt.Columns[i].ColumnName, "@");
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < columnsCount-2; j++)
                        worksheet.Cells[i + 1, j] = new Cell(dt.Rows[i][j] == DBNull.Value ? "" : dt.Rows[i][j].ToString(), "@");
                }

                workbook.Worksheets.Add(worksheet);
                string path1="~/Lgr/ExportedFiles" + "\\" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                path = System.Web.HttpContext.Current.Server.MapPath(path1);
                workbook.Save(path);
                OutputFile(".xls",path);
           
            }
            catch (Exception ex)
            {
                path = null;
                msg = ex.Message;
            }
            return path;
        }


 private void OutputFile(string contentType, string generatedFileName)
        {
            FileInfo file = new FileInfo(generatedFileName);
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpContext.Current.Server.UrlEncode(file.Name));
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = contentType;
            Response.WriteFile(file.FullName);
            //Response.End();
        }












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值