[英]C# OpenXML make Excel file downloadable
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ExcelReportsController : Controller
{
private ExcelContext db = new ExcelContext();
[Route("/ExportToExcel")]
[HttpGet]
public void ExportPersonsToExcel()
{
var sqlParameters = new List<SqlParameter>();
sqlParameters.Add(new SqlParameter("@id", "1"));
var persons = db.Database.SqlQuery<TestExcel>("SELECT * FROM persons(@id)", sqlParameters.ToArray()).ToArray();
DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));
using (SpreadsheetDocument document = SpreadsheetDocument.Create("TestNewData.xlsx", SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
sheets.Append(sheet);
Row headerRow = new Row();
List<String> columns = new List<string>();
foreach (DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in table.Rows)
{
Row newRow = new Row();
foreach (String col in columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString());
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookPart.Workbook.Save();
}
}
}
}
I have the following code, but when i ask for the excel file, nothing happens.我有以下代码,但是当我询问 excel 文件时,没有任何反应。 I want it to download automatically when I enter that URL.
我希望它在我输入 URL 时自动下载。 Any solutions?
有什么解决办法吗?
Maybe a stream?也许是 stream? But how would I implement that?
但是我将如何实现呢? I'm pretty new using this library - so bear with me.
我是使用这个库的新手——所以请耐心等待。
First, change the return type of your method to IActionResult
首先,将方法的返回类型更改为
IActionResult
Then, after the using
block, add this:然后,在
using
块之后,添加以下内容:
var stream = System.IO.File.Open("TestNewData.xlsx", FileMode.Open);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
It creates a FileStream
from your file, then returns a FileStreamResult
.它从您的文件创建一个
FileStream
,然后返回一个FileStreamResult
。 The long string is the MIME type for Microsoft Excel (OpenXML) .长字符串是Microsoft Excel (OpenXML) 的 MIME 类型。 Note,
FileStreamResult
should automatically dispose the stream.注意,
FileStreamResult
应该自动处理stream。
If you wish to provide a name for the downloaded file, you can use an overloaded version of File
, so just pass a third argument (of type string), like this:如果您希望为下载的文件提供名称,可以使用重载版本的
File
,因此只需传递第三个参数(字符串类型),如下所示:
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "CustomName.xlsx");
I found a solution.我找到了解决方案。
We have to return a HttpResponseMessage.我们必须返回一个 HttpResponseMessage。 Then after the "using" block, we add the following code:
然后在“使用”块之后,我们添加以下代码:
var path = "TestNewData.xlsx";
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return result;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.