mvc导出excel问题,谢谢各位帮忙

nitaiyoucala 2017-08-10 03:16:19
下面是我的通用类,请问控制器里面的action怎么写?怎么调用这个方法

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

ISheet sheet = null;
if (!string.IsNullOrEmpty(sheetName))
{
sheet = xssfworkbook.CreateSheet(sheetName);
}
else
{
sheet = xssfworkbook.CreateSheet("Sheet1");
}

//表头
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);

HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", file));
HttpContext.Current.Response.AddHeader("Content-Length", stream.ToArray().Length.ToString());
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
xssfworkbook = null;
stream.Close();
stream.Dispose();
HttpContext.Current.Response.End();
}


...全文
262 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-一个大坑 2017-08-14
  • 打赏
  • 举报
回复
引用 2 楼 FightForMyLove 的回复:
用ajax 异步吧 ,上传文件 和 导出文件 用ajax吧。 给你一个 百度链接 https://zhidao.baidu.com/question/1574377976605378500.html
不是说ajax不能返回excel吗?
kinshines 2017-08-14
  • 打赏
  • 举报
回复
你的代码是WebForm时代的,在MVC时代,推荐使用FileResult
nitaiyoucala 2017-08-11
  • 打赏
  • 举报
回复
引用 2 楼 FightForMyLove 的回复:
用ajax 异步吧 ,上传文件 和 导出文件 用ajax吧。 给你一个 百度链接 https://zhidao.baidu.com/question/1574377976605378500.html
不是这个啊。。。。。
chen510103032 2017-08-11
  • 打赏
  • 举报
回复
Action返回null就可以了。 Response.Clear(); Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8)); Response.ContentEncoding = System.Text.Encoding.GetEncoding("shift_jis"); Response.Write(strCsv.ToString()); Response.Flush(); Response.End(); strCsv.Clear(); strCsv = null; _tracelog?.Debug("[ACT] <= KeyWordManage/ExportKeyWordDataToCsv()"); return null;
首推未来 2017-08-10
  • 打赏
  • 举报
回复
用ajax 异步吧 ,上传文件 和 导出文件 用ajax吧。 给你一个 百度链接 https://zhidao.baidu.com/question/1574377976605378500.html
全栈极简 2017-08-10
  • 打赏
  • 举报
回复
MVC有专门的FileResult返回文件,http://www.cnblogs.com/zhangchunyu/articles/5805008.html

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧