Web设计器如何自定义保存报表到数据库并读取预览报表
本帖最后由 KearneyKang 于 2023-9-6 15:12 编辑在线设计器是基于MVC 项目开发的,默认的是将报表保存到服务器的文件夹上面。但往往有很多应用场景是需要将报表保存到数据库后期报表加载预览的时候从数据库中读取报表文件内容并且预览。
下面给详细讲解如何把报表文件通过 Xml 的形式自定义保存在Sqllite数据库中
1、首先如果要自定义报表的保存,那么就需要修改 Startup.cs 的 UseCustomStore 的方法
通过 SQLExpressResourcesService()方法进行保存自定义
var resourcesService = new SQLExpressResourcesService();
app.UseDesigner(config => {
config.UseCustomStore(resourcesService);
}); SQLExpressResourcesService实现部分代码
自定义保存
public string SaveReport(string name, Report report, bool isTemporary)
{
if (!isTemporary)
{
using (var conn = new SQLiteConnection(connString))
{
conn.Open();
var reportXml = ReportConverter.ToXml(report);
string id = name.Substring(0, name.IndexOf(".rdlx"));
string sql = @"INSERT INTO reportInfo (Id, Name, Type, reportXml)
VALUES (@id, @name, @type, @reportXml)"; // 替换为你的表名
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id); // 替换为实际的Id值
cmd.Parameters.AddWithValue("@name", name); // 替换为实际的Name值
cmd.Parameters.AddWithValue("@type", "RDL"); // 替换为实际的Type值
cmd.Parameters.AddWithValue("@reportXml", reportXml); // 替换为实际的reportXml值
cmd.ExecuteNonQuery();
}
return name;
}
else
{
var reportXml = ReportConverter.ToXml(report);
byte[] xmlBytes = reportXml;
string currentDir = AppDomain.CurrentDomain.BaseDirectory;
// 指定报表文件的缓存路径
string cachePath = currentDir + @"resources\report.rdlx";
try
{
// 将报表数据写入文件
File.WriteAllBytes(cachePath, reportXml);
Console.WriteLine("报表文件已成功缓存到路径:" + cachePath);
}
catch (Exception ex)
{
Console.WriteLine("报表文件缓存失败:" + ex.Message);
return null;
}
return cachePath;
}
}
自定义读取报表
public Report GetReport(string id)
{
GrapeCity.ActiveReports.PageReportModel.Report rpt = null;
using (var conn = new SQLiteConnection(connString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText =
"SELECT id, reportXml FROM reportInfo WHERE id = @id";
cmd.Parameters.AddWithValue("@id", id);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
using (var readStream = reader.GetStream(1))
using (var outputStream = new MemoryStream())
{
readStream.CopyTo(outputStream);
rpt= ReportConverter.FromXML(outputStream.ToArray());
}
}
}
}
}
return rpt;
}报表自定义预览
app.UseReporting(settings =>
{
settings.UseCompression = true;
settings.UseCustomStore(report =>
{
PageReport rep = new PageReport();
//string path = System.Web.Hosting.HostingEnvironment.MapPath("~/");
rep.Load(new FileInfo(HttpUtility.UrlDecode(report)));
return rep.Report;
});
});最终自定义保存demo下载
页:
[1]