Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Page.aspx page "Export excel" button, the page jump to page Test.aspx
<a id="exportExcBtn" class="easyui-linkbutton" iconcls="" plain="true" >导出excel</a>
$("#exportExcBtn").attr("href", "exportExcel.aspx?param=" +Page.aspx页面需要传到exportExcel.aspx页面的值);
exportExcel.aspx page empty page, the back-end exportExcel.aspx.cs file write functions and methods
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();
}
Click "Export excel" button, the page jump to exportExcel.aspx page, download to a local browser