Guardando archivo en objeto de respuesta

Guardando archivo en objeto de respuesta

También es posible generar un archivo dinámicamente y enviarlo directamente al navegador del cliente. Para hacerlo, use una versión sobrecargada especial del método Save que acepta los siguientes parámetros:

La enumeración ContentDisposition determina si el archivo que se envía al navegador proporciona la opción de abrirse directamente en el navegador o en una aplicación asociada con .xls/.xlsx u otra extensión.

La enumeración contiene los siguientes tipos de guardado predefinidos:

Tipo Descripción
Archivo adjunto Envía la hoja de cálculo al navegador y se abre en una aplicación como un archivo adjunto asociado con .xls/.xlsx u otras extensiones
En línea Envía el documento al navegador y presenta una opción para guardar la hoja de cálculo en el disco o abrir dentro del navegador

Archivos XLS

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
HttpResponse Response = null;
// Load your source workbook
Workbook workbook = new Workbook();
if (Response != null)
{
// Save in Excel2003 XLS format
workbook.Save(Response, dataDir + "output.xls", ContentDisposition.Inline, new XlsSaveOptions());
Response.End();
}

Archivos XLSX

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
HttpResponse Response = null;
// Load your source workbook
Workbook workbook = new Workbook();
if (Response != null)
{
// Save in Xlsx format
workbook.Save(Response, dataDir + "output.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions());
Response.End();
}

Archivos PDF

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
HttpResponse Response = null;
// Creating a Workbook object
Workbook workbook = new Workbook();
if (Response != null)
{
// Save in Pdf format
workbook.Save(Response, dataDir + "output.pdf", ContentDisposition.Attachment, new PdfSaveOptions());
Response.End();
}

Nota

Debido al objeto “System.Web.HttpResponse” que no está incluido en .NET5 y .Netstandard, Por lo tanto, esta función no existe en la versión Aspose.Cells .NET5 y .Netstandard, puede consultar el siguiente código para guardar el archivo en el flujo, y luego realizar operaciones en el flujo.

public async Task<IActionResult> DownloadExcel()
{
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir + "Book1.xlsx";
// Load your source workbook
Workbook workbook = new Workbook(filePath);
// Save the workbook to a memory stream
var stream = new MemoryStream();
workbook.Save(stream, SaveFormat.Xlsx);
// Reset the position of the stream to 0
stream.Position = 0;
// Set the content type and file name
var contentType = "application/octet-stream";
var fileName = "output.xlsx";
// Set the response headers
Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
Response.ContentType = contentType;
// Write the file contents to the response body stream
await stream.CopyToAsync(Response.Body);
// Close the file stream
stream.Dispose();
// Return the response
return new EmptyResult();
}