This sample project shows how to export the report to various formats. For this action, it is enough to use the special
StiReportResponse
class that implements the methods of all export formats. These methods take the input of all the necessary parameters to configure exports.
For example, implementing a several popular export formats for various reports. Add selection lists on the ASPX page, also add buttons for export and call the preview page of the report in the web viewer:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Export_Report_from_Code.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Export Report from Code</title>
</head>
<body>
<form id="form1" runat="server">
<h2><span style="color: #0066ff">Export Example</span></h2>
<table>
<tr>
<td width="200px">
<strong>Select Report:</strong>
</td>
<td width="200px">
<strong>Select Output Format:</strong>
</td>
</tr>
<tr>
<td>
<asp:ListBox ID="ListBoxReports" runat="server" Height="100px">
<asp:ListItem Selected="True">Anchors</asp:ListItem>
<asp:ListItem>MasterDetail</asp:ListItem>
<asp:ListItem>MultiColumnList</asp:ListItem>
<asp:ListItem>SimpleGroup</asp:ListItem>
<asp:ListItem>SimpleList</asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:ListBox ID="ListBoxFormats" runat="server" Height="100px">
<asp:ListItem Selected="True">Pdf</asp:ListItem>
<asp:ListItem>Html</asp:ListItem>
<asp:ListItem>Xls</asp:ListItem>
<asp:ListItem>Txt</asp:ListItem>
<asp:ListItem>Rtf</asp:ListItem>
</asp:ListBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="ButtonPreview" runat="server" Text="Preview" onclick="ButtonPreview_Click" />
</td>
<td>
<asp:Button ID="ButtonExport" runat="server" Text="Export" onclick="ButtonExport_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
In the
ButtonExport_Click()
event loads the report, connects to the data and exports the report in the selected format. To export a report using the static methods of the
StiReportResponse
class:
protected void ButtonExport_Click(object sender, EventArgs e)
{
var report = new StiReport();
report.Load(Server.MapPath($"Reports\\{ListBoxReports.SelectedItem.Text}.mrt"));
switch (ListBoxFormats.SelectedIndex)
{
case 0:
StiReportResponse.ResponseAsPdf(report);
break;
case 1:
StiReportResponse.ResponseAsHtml(report);
break;
case 2:
StiReportResponse.ResponseAsXls(report);
break;
case 3:
StiReportResponse.ResponseAsText(report);
break;
case 4:
StiReportResponse.ResponseAsRtf(report);
break;
}
}
The selected report can be displayed in the viewer. For this purpose, use the
ButtonPreview_Click()
event which saves the report name in the session and redirects to the
Report.aspx
page with the report viewer:
protected void ButtonPreview_Click(object sender, EventArgs e)
{
Session["reportname"] = ListBoxReports.SelectedItem.Text;
Response.Redirect("Report.aspx");
}
На скриншоте ниже Вы можете увидеть результат выполнения данного кода: