页面视图上——按钮
$('#ExportSysOperateLogs').linkbutton({ iconCls: 'icon-excel' });
$("#ExportSysOperateLogs").click(function () { ExportSysOperateLogs(); });
页面视图上——按钮事件
function ExportSysOperateLogs() {
var Text = "操作日志信息";
var checkId = $("#clientTable").datagrid('getRows');
if (checkId.length > 0) {
var url = "/Queycount/ExportSysOperateLogs?"
+ "Startbirthday=" + Startbirthday
+ "&Endbirthday=" + Endbirthday
+ "&Text=" + Text;
$("#frmExportToExcels").attr("action", url).submit();
} else {
$.messager.alert("提示", "请你查询数据!");
}
}
from事件
<form id="frmExportToExcels" action="" method="post"></form>
控制器中
public ActionResult ExportSysOperateLogs()
{
AddTmLog("导出", "日志", "导出日志信息");
string Startbirthday = Request["Startbirthday"];
string Endbirthday = Request["Endbirthday"];
var data = new WJ.Terminal.Bll.Jiuding.JiudingBll().GetSysOperateLogs(Startbirthday, Endbirthday);
string Text = Request["Text"];
List<ExportSysOperateLogs> ejmList = new List<ExportSysOperateLogs>();
ExportSysOperateLogs ejm = null;
foreach (var item in data)
{
ejm = new ExportSysOperateLogs()
{
SOL_ID = item.SOL_ID,
OPERATE_TIME = item.OPERATE_TIME,
OPERATE_TYPE = item.OPERATE_TYPE,
PARAMA = item.PARAMA,
PARAMA_SOURCE = item.PARAMA_SOURCE,
RETURNS_RESULTS = item.RETURNS_RESULTS,
REMARK = item.REMARK
};
ejmList.Add(ejm);
}
if (ejmList.Count > 0)
{
string[] cellNames = { "系统日志ID", "操作时间", "操作类型", "参数", "源参数", "返回结果", "备注" };
string fileName = "操作日志信息_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
return new DownloadFileExcelHeader(cellNames, fileName, ejmList, Text);
}
return RedirectToAction("/SysOperateLogs");
}
导出有表头excel文件
public class DownloadFileExcelHeader : ActionResult
{
public string fileName { get; set; }
HSSFWorkbook book = new HSSFWorkbook();
/// <summary>
/// 导出excel函数
/// </summary>
/// <param name="cellNames">每列标题</param>
/// <param name="pFileName">excel文件名</param>
/// <param name="df">导出List数据集合</param>
/// <param name="strHeaderText">excel文本标题</param>
public DownloadFileExcelHeader(string[] cellNames, string pFileName, IList df, string strHeaderText)
{
fileName = pFileName;
//普通单元格样式
ICellStyle cellstyle = book.CreateCellStyle();
cellstyle.Alignment = HorizontalAlignment.Left; //水平居左
cellstyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
cellstyle.WrapText = false; //自动换行
IFont cellfont = book.CreateFont();
cellfont.FontHeightInPoints = 10; //11号字体
cellstyle.SetFont(cellfont);
//列表头单元格样式
ICellStyle cellheadstyle = book.CreateCellStyle();
cellheadstyle.Alignment = HorizontalAlignment.Center;
cellheadstyle.VerticalAlignment = VerticalAlignment.Center;
IFont cellheadfont = book.CreateFont();
cellheadfont.FontHeightInPoints = 10;
cellheadfont.Boldweight = (short)FontBoldWeight.None; //字体是否加粗
cellheadstyle.SetFont(cellheadfont);
//船名航次
ICellStyle VesselVoystyle = book.CreateCellStyle();
VesselVoystyle.Alignment = HorizontalAlignment.Left;
VesselVoystyle.VerticalAlignment = VerticalAlignment.Bottom;
VesselVoystyle.WrapText = true; //自动换行
IFont VesselVoyfont = book.CreateFont();
VesselVoyfont.FontHeightInPoints = 10;
VesselVoyfont.Boldweight = (short)FontBoldWeight.Bold; //字体是否加粗
VesselVoystyle.SetFont(VesselVoyfont);
DataTable grid = ToDataTableTow(df);
ISheet sheet = book.CreateSheet(System.IO.Path.GetFileNameWithoutExtension(pFileName));
sheet.IsPrintGridlines = true; //打印时显示网格线
sheet.DisplayGridlines = true;//查看时显示网格线
//sheet.DefaultRowHeightInPoints = 25; 这种默认设置不起作用
//sheet.SetColumnWidth(0, 20 * 256);//预订人宽度
sheet.DefaultColumnWidth = 18;
int rowIndex = 2;//开始添加数据的行数
int colIndex = 0;
//int vesIndex = 0;
//excel文本标题
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
//excel文本标题样式
HSSFCellStyle headStyle = (HSSFCellStyle)book.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
HSSFFont font = (HSSFFont)book.CreateFont();
font.FontHeightInPoints = 18;
font.Boldweight = 500;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, cellNames.Length - 1));
//设置
IRow row = sheet.CreateRow(1);
row.HeightInPoints = 18;
//列标题
for (int i = 0; i < cellNames.Length; i++)
{
ICell cell = row.CreateCell(colIndex);
cell.SetCellValue(cellNames[i].ToString());
cell.CellStyle = cellheadstyle;
colIndex++;
}
//导入数据行
foreach (DataRow rows in grid.Rows)
{
colIndex = 0;
row = sheet.CreateRow(rowIndex);
foreach (DataColumn col in grid.Columns)
{
ICell cell = row.CreateCell(colIndex);
cell.SetCellValue(rows[col.ColumnName].ToString());
cell.CellStyle = cellstyle;
colIndex++;
}
rowIndex++;
}
}
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <returns></returns>
public static DataTable ToDataTableTow(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
/// <summary>
/// 重写返回方法
/// </summary>
/// <param name="context"></param>
public override void ExecuteResult(ControllerContext context)
{
bool isFireFox = false;
if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") != -1)
{
isFireFox = true;
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
byte[] bytes = ms.ToArray();
book = null;
ms.Close();
ms.Dispose();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//通知浏览器下载文件而不是打开
if (isFireFox == true)
{
fileName = "\"" + fileName + "\"";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
}
else
{
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
}
//HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
总:如果没有from事件,会出现点击导出按钮没效果