寻求具备Excel导出功能的2sxc应用示例及实现方案
从2sxc应用导出数据至Excel的实现方案
2sxc本身没有内置Excel导出功能,但可以通过两种方式实现:基于现有API自定义开发,或者使用官方/社区的预制示例应用。
一、自定义开发实现(核心思路)
借助.NET的Excel生成库(如EPPlus、NPOI),结合2sxc的数据API快速实现导出逻辑,步骤如下:
- 获取目标数据:通过2sxc的
App.Data["YourEntityName"]获取要导出的实体数据 - 生成Excel文件:用Excel库创建工作簿、填充表头和数据行
- 输出文件流:设置响应头为Excel格式,让浏览器下载文件
代码示例
1. Razor视图添加导出按钮
<a href="@Dnn.Path("/DesktopModules/2sxc/Api/App/Content/ExportExcel?entity=YourEntity")" class="btn btn-primary">导出至Excel</a>
2. 创建WebApi控制器(在应用的App_Code目录下)
using System.IO; using System.Web.Http; using DotNetNuke.Web.Api; using OfficeOpenXml; using System.Linq; using System; [DnnModuleAuthorize(AccessLevel = DotNetNuke.Security.SecurityAccessLevel.View)] public class ExportController : SxcApiController { [HttpGet] public IHttpActionResult ExportExcel(string entity) { var dataSet = App.Data[entity]; if (dataSet == null || !dataSet.Any()) return NotFound(); var dataList = dataSet.ToList(); var attributes = dataList.First().EntityMetadata.Attributes; using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("导出数据"); // 写入表头 for (int colIndex = 0; colIndex < attributes.Count; colIndex++) { worksheet.Cells[1, colIndex + 1].Value = attributes[colIndex].Name; worksheet.Cells[1, colIndex + 1].Style.Font.Bold = true; } // 写入数据行 for (int rowIndex = 0; rowIndex < dataList.Count; rowIndex++) { var item = dataList[rowIndex]; for (int colIndex = 0; colIndex < attributes.Count; colIndex++) { worksheet.Cells[rowIndex + 2, colIndex + 1].Value = item.Get(attributes[colIndex].Name); } } // 自动调整列宽 worksheet.Cells.AutoFitColumns(); var stream = new MemoryStream(); package.SaveAs(stream); stream.Position = 0; var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StreamContent(stream) { Headers = { System.Net.Http.Headers.ContentDispositionHeaderValue.Parse($"attachment; filename={entity}_{DateTime.Now:yyyyMMddHHmm}.xlsx"), ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") } } }; return ResponseMessage(response); } } }
注意事项
- 需在2sxc应用中安装EPPlus包(可通过Dnn的NuGet管理器或手动添加引用)
- 确保当前用户拥有目标实体的读取权限
- 可根据需求扩展:添加样式、过滤数据、处理特殊格式(如日期、货币)
二、预制示例应用
2sxc官方应用商店中存在现成的Excel导出示例应用,比如Excel Export Kit,这类应用已经封装好导出逻辑,导入后只需配置要导出的实体名称即可使用,无需手动编写代码。
内容的提问来源于stack exchange,提问作者MBouwman
相关产品推荐
相关产品推荐

