导出excel文件通过浏览器下载到本地(js+C#后台)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_41085761/article/details/88420551

Page.aspx页面"导出excel"按钮,页面跳转到Test.aspx页面
到exportExcel.aspx页面调用exportExcel.aspx.cs后台方法生成excel通过浏览器下载至本地

<a id="exportExcBtn" class="easyui-linkbutton" iconcls="" plain="true" >导出excel</a>
$("#exportExcBtn").attr("href", "exportExcel.aspx?param=" +Page.aspx页面需要传到exportExcel.aspx页面的值);

exportExcel.aspx页面为空页面,后端exportExcel.aspx.cs文件写入函数及方法

protected void Page_Load(object sender, EventArgs e)
        {
        string filename = "excel导出表";
        DataTable dt = getdataTable(Request["param"].ToString());//从数据库取出datatable
        ExportExcel(dt, filename);
        }
public void ExportExcel(DataTable dt, string filename)
{
    //新建一个 Excel 工作簿
    ExcelPackage package = new ExcelPackage();
    // 添加一个 sheet 表
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("tablenew");
    int rowIndex = 1;   // 起始行为 1
    int colIndex = 1;   // 起始列为 1
    //设置列名
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[rowIndex, colIndex + i].Value = dt.Columns[i].ColumnName;
        //自动调整列宽,也可以指定最小宽度和最大宽度
        worksheet.Column(colIndex + i).AutoFit();
    }
    // 跳过第一列列名
    rowIndex++;
    //写入数据
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        for (int j = 0; j < dt.Columns.Count; j++)
            {
              worksheet.Cells[rowIndex + i, colIndex + j].Value = dt.Rows[i][j].ToString();
            }
            //自动调整行高
        worksheet.Row(rowIndex + i).CustomHeight = true;
    }
     //设置字体,也可以是中文,比如:宋体
    //worksheet.Cells.Style.Font.Name = "Arial";
    //字体加粗
    //worksheet.Cells.Style.Font.Bold = true;
    //字体大小
    //worksheet.Cells.Style.Font.Size = 12;
    //字体颜色
    //worksheet.Cells.Style.Font.Color.SetColor(System.Drawing.Color.Black);
    //单元格背景样式,要设置背景颜色必须先设置背景样式
    //worksheet.Cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
    //垂直居中
    worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
    //水平居中
    worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
    //直接获取字节数组
    byte[] bytes = package.GetAsByteArray();
    //调用下面的方法输出到浏览器下载
    OutputClient(bytes, filename);
     worksheet.Dispose();
    package.Dispose();
}

点击"导出excel"按钮后,页面跳转至exportExcel.aspx页面,后通过浏览器下载至本地

猜你喜欢

转载自blog.csdn.net/weixin_41085761/article/details/88420551