Live Razor Page Samples
Excel Report with Picture
This sample shows how to create a new workbook, add a picture, and stream it to Microsoft Excel.
Supporting Files
The following file is utilized by this sample:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Website.Pages.Support.Samples.RazorPages.Reporting
{
public partial class ExcelReportPictureModel : PageModel
{
public FileResult OnGet()
{
// Create a new empty workbook and get the first sheet.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
// Get the width and height of the picture in pixels and convert to
// points for use in the call to AddPicture. This step is only
// necessary if the actual picture size is to be used and that size
// is unknown. Another option is to calculate the width and height
// in row and column coordinates in the same manner as left and top below.
double width;
double height;
System.Drawing.Image image = System.Drawing.Image.FromStream(INTERNAL_GetSupportingFileStream("sg-banner.png"));
System.Drawing.Image image = System.Drawing.Image.FromFile("files/ssgear.gif");
using (image)
{
width = image.Width * 72.0 / image.HorizontalResolution;
height = image.Height * 72.0 / image.VerticalResolution;
}
// Calculate the left and top placement of the picture by converting
// row and column coordinates to points. Use fractional values to
// get coordinates anywhere in between row and column boundaries.
SpreadsheetGear.IWorksheetWindowInfo windowInfo = worksheet.WindowInfo;
double left = windowInfo.ColumnToPoints(1.5);
double top = windowInfo.RowToPoints(1.5);
// Add the picture from file.
worksheet.Shapes.AddPicture(INTERNAL_GetSupportingFileBytes("sg-banner.png"), left, top, width, height);
//worksheet.Shapes.AddPicture(imageFile, left, top, width, height);
// Save workbook to stream using the Open XML (*.xlsx) file format compatible with Excel 2007 and later.
System.IO.Stream workbookStream = workbook.SaveToStream(SpreadsheetGear.FileFormat.OpenXMLWorkbook);
// Reset position to the beginning of the stream.
workbookStream.Seek(0, System.IO.SeekOrigin.Begin);
// Stream the Excel workbook to the client.
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = "SpreadsheetGear-Sample-ExcelReportPicture.xlsx";
return File(workbookStream, contentType, fileName);
}
}
}