我制作了一个简单的网页,其中包含一些可以操作的数据,并使用 ClosedXML 将该列表转换为 exel 文档。 数据处理工作正常。问题出在 exe 转换上。
我应该如何编写网页以将文档保存在客户端?当我在我的电脑上测试时,下面的代码可以在本地运行,但尝试在服务器上远程执行该操作会提示错误。
运行时错误 描述:服务器上发生应用程序错误。此应用程序当前的自定义错误设置阻止远程查看应用程序错误的详细信息(出于安全原因)。但是,它可以通过本地服务器计算机上运行的浏览器查看。
详细信息:要在远程计算机上查看此特定错误消息的详细信息,请在位于当前 Web 应用程序根目录的“web.config”配置文件中创建一个标记。然后,该标签的“模式”属性应设置为“关闭”。
我还不熟悉如何犯自定义错误,但我确实知道问题一定是我尝试保存文件的方式。应用程序尝试将文档保存到服务器的C盘上。 虽然我需要它来将文件保存在客户端的 PC 上。
查看:
@using (Html.BeginForm("Export", "Home"))
{
<button class="btn btn-primary btn" type="submit" name="dummy" value="">Export Excel</button>
}
控制器:
public ActionResult Export() //Export Exel
{
if (staticList.Count > 0)
{
// here be the convertion of the data to exel using ClosedXML
wb.SaveAs("C:\\BT.xlsx");
ViewData["sentence"] = "Export made";
}
return View("Index", staticList);
}
从 Web 应用程序将文件导出到客户端计算机需要将文件作为带有适当标头的响应发送。在当前代码中,您将文件保存在
server's C drive
上,但您应该将其作为 response
发送到客户端的浏览器,以便可以将其下载到客户端的计算机。要实现此目的,您可以按如下方式修改代码:
public ActionResult Export()
{
if (staticList.Count > 0)
{
using (var wb = new XLWorkbook())
{
// Add data to the Excel workbook using ClosedXML
var ws = wb.Worksheets.Add("Sheet1");
// Populate the worksheet with data from your staticList
// For example:
for (int i = 0; i < staticList.Count; i++)
{
ws.Cell(i + 1, 1).Value = staticList[i].Property1;
ws.Cell(i + 1, 2).Value = staticList[i].Property2;
// Add more properties as needed
}
// Prepare the file content
var stream = new MemoryStream();
wb.SaveAs(stream);
// Set the response headers to prompt the user to download the file
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=BT.xlsx");
Response.BinaryWrite(stream.ToArray());
Response.End();
}
}
return View("Index", staticList);
}
插入表格文档页面显示了如何使用
InsertTable
将列表直接加载到电子表格中,并使用属性名称作为列。该方法返回一个表对象,可用于应用样式、排序等:
var list = new List<Person>();
...
var peopleTable= ws.Cell(7, 6).InsertTable(list);
...
peopleTable.Theme = XLTableTheme.TableStyleLight10;
wb.SaveAs("InsertingData.xlsx");
要将数据返回给调用者,请将工作簿保存到 MemoryStream 并使用
File
方法而不是 View
返回它:
public ActionResult Export()
{
...
using var stream = new System.IO.MemoryStream();
wb.SaveAs(stream);
var content = stream.ToArray();
return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "People.xlsx");
}