A la hora de trabajar con el diseñador de informes online FastReport normalmente tenemos que cargar nustro modelo de informe en este y luego, después de editar, descargarlos. Hoy vamos a echar un vistazo a cómo se puede hacerlo en el contexto de una aplicación ASP.Net Core.
Cree una aplicación ASP.Net Core. Añada las bibliotecas FastReport.Net a esta utilizando NuGet. Utilice la fuente de paquetes local – la carpeta Muget del directorio de instalación FastReport.Net. Instale dos paquetes: FastReport.Core y FastReport.Web.
Añada la carpeta App_Date a la carpeta wwwroot. Coloque la fuente de datos para los informes demo en esta (nwind.xml).
También añadimos una carpeta con un diseñador de informes que ha descargado desde el sitio web oficial de FastReports www.fast-report.com a wwwroot.
Para utilizar las bibliotecas FastReport en su proyecto, tiene que añadir una línea de código al archivo Startup.cs:
1 2 3 4 5 6 7 8 9 |
public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { … app.UseFastReport(); … } } |
Vamos a proceder a la edición del corolador HomeController.
Tenemos que crear 4 métodos que sirven para: mostrar el diseñador de informes con el informe cargado, cargar el archivo en el servidor, generar un archivo para la descarga y guardar el informe modificado en el servidor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
public class HomeController : Controller { public static string ReportName; public ActionResult Index(string filepath) { Task.WaitAll(); WebReport webReport = new WebReport(); // Web report object webReport.Width = "1000"; webReport.Height = "1000"; string report_path = GetReportPath(); // Path to the folder with reports System.Data.DataSet dataSet = new System.Data.DataSet(); dataSet.ReadXml(report_path + "nwind.xml"); // Read the database webReport.Report.RegisterData(dataSet, "NorthWind"); // Register data in the report if (System.IO.File.Exists(report_path + "report.frx")) { webReport.Report.Load(report_path + "report.frx"); } // If you use a cache, then load a report from it. if (filepath != null) { webReport.Report.Load(filepath); } // Set the settings Online-Designer webReport.Mode = WebReportMode.Designer; webReport.DesignScriptCode = false; webReport.Debug = true; webReport.DesignerPath = @"WebReportDesigner/index.html"; webReport.DesignerSaveCallBack = "Home/SaveDesignedReport"; ViewBag.WebReport = webReport; // pass the report to View ViewData["reportName"] = ReportName = Path.GetFileName(filepath); return View(); } private string GetReportPath() { return "wwwroot/App_Data/"; } [HttpPost] public async Task<IActionResult> UploadFile(List<IFormFile> file) { if (file == null || file[0].Length == 0) return Content("file not selected"); // Form the path to the file var path = Path.Combine( Directory.GetCurrentDirectory(), GetReportPath(), file[0].FileName); // Save the file on the server using (var stream = new FileStream(path, FileMode.Create)) { await file[0].CopyToAsync(stream); } // Move on to display the report designer with the loaded report template. return RedirectToAction("Index", "Home", new { filepath = path }); } [HttpPost] public IActionResult Download(string filename) { // Form the path to the file on the server var path = Path.Combine(Directory.GetCurrentDirectory(), GetReportPath(), filename); if (System.IO.File.Exists(path)) { // Form the result of POST request var bytes = System.IO.File.ReadAllBytes(path); Response.Body.Write(bytes, 0, bytes.Length); } return new OkResult(); } [HttpPost] public IActionResult SaveDesignedReport(string reportID, string reportUUID) { var path = Path.Combine(Directory.GetCurrentDirectory(), GetReportPath()); ViewBag.Message = String.Format("Confirmed {0} {1}", reportID, reportUUID); // Set the message for representation Stream reportForSave = Request.Body; // Write the result of the Post-request to the stream. string pathToSave = System.IO.Path.Combine(path, ReportName); // Form the path to save the file using (FileStream file = new FileStream(pathToSave, FileMode.Create)) // Stream creation { reportForSave.CopyTo(file); // Save query result to file return View(); } } } |
Al mostrar una página web, lo primero que verá es un diseñador de informes con un modelo en blanco. Y después de cargar el archivo del informe en el servidor, aparecerá el diseñador con el modelo cargado.
Fíjese que utilizamos ViewData para pasar el nombre del informe a la vista.
Ahora remplace la vista por el método Index:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
@{ ViewData["Title"] = "Home Page"; } <form asp-controller="Home" asp-action="UploadFile" method="post" enctype="multipart/form-data"> <input id="file" type="file" name="file" accept=".frx" /> <button type="submit">Загрузить файл</button> <input type="Button" value="Скачать отчет" onclick="GetFile()" /> </form> @await ViewBag.WebReport.Render() <script language="javascript" type="text/javascript"> function GetFile() { $.ajax({ url: '/Home/Download', type: 'POST', data: { filename: '@ViewData["reportName"]' }, xhrFields: { responseType: 'blob' }, success: function (data) { var tag = document.createElement('a'); var url = window.URL.createObjectURL(data); tag.href = url; tag.download = '@ViewData["reportName"]'; document.body.append(tag); tag.click(); tag.remove(); window.URL.revokeObjectURL(url); } }); }; </script> |
Aquí utilizamos dos maneras de mandar solicitudes al servidor: a través del formulario y con la solicitud ajas. En el primer caso, cargamos el archivo y, como seguimos con la necesidad de actualizar el diseñador de informes, podemos descuidarnos de actualizar la página entera. En el segundo caso, al descargar el archivo del informe, no queremos actualizar la página y es mejor utilizar la solicitud ajas. No podemos organizar la descarga del archivo solo con la solicitud ajas, por lot tanto, al proceder al resultado de la solicitud, creamos una pestaña con un hipervínculo al archivo que se está descargando.
Para el método SaveDesignedReport en el controlador, necesita crear una vista con el siguiente código:
@ViewBag.Message
Ya está. Arranque la aplicación. Primero vemos el diseñador de informes con un modelo en blanco.
Haga clic en el botón Select file y seleccione un modelo de informe para descargarlo.
Haga clic en el botón Upload file:
Y obtenemos un diseñador de informe con un modelo cargado. Podemos hacer cuaquier cosa con el modelo y guardarlo. Y ahora haga clic en el botón Download Report.
El navegador descarga el archivo del informe:
De esta manera, hemos realizado lo que qeríamos, es decir, hemos creado un editor de informes completo que es capaz de cargar, guardar y descargar informes..