Hi satabeach,
There is no way to get the row count per page in report. So to export each page to separate excel you need to export the DataSet that you are assigned to the ReportDataSource and need to assign the row size to export per page in code behind based on the size you have provided in the design time to the report.
Check this example. Now please take its reference and correct your code.
For this example i have used ClosedXml library for exporting to excel.
You can refer below article for more details.
HTML
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="600" Height="320">
</rsweb:ReportViewer>
<asp:Button Text="Export" ID="btnExport" runat="server" OnClick="btnExport_Click" />
Namespace
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;
using ClosedXML.Excel;
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Report.rdlc");
Customers dsCustomers = GetData("select * from customers");
ReportDataSource datasource = new ReportDataSource("Customers", dsCustomers.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
}
}
private Customers GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (Customers dsCustomers = new Customers())
{
sda.Fill(dsCustomers, "DataTable1");
return dsCustomers;
}
}
}
}
protected void btnExport_Click(object sender, EventArgs e)
{
// Assign record per page in the excel as per the report.
int rowPerPage = 10;
Customers dsCustomers = GetData("select CustomerId,ContactName,City,Country from customers");
DataTable dt = new DataTable();
for (int j = 0; j < dsCustomers.Tables[0].Columns.Count; j++)
{
string columnName = dsCustomers.Tables[0].Columns[j].ColumnName;
dt.Columns.Add(new DataColumn(columnName));
}
for (int i = 0; i < dsCustomers.Tables[0].Rows.Count; i++)
{
if ((i > 0 && (i % rowPerPage == 0)))
{
GenerateExcel(dt, @"C:\Users\dharmendra\Desktop\Excels\", "Test" + i);
dt.Clear();
}
DataRow dr = dsCustomers.Tables[0].Rows[i];
dt.Rows.Add(dr.ItemArray);
if (i == dsCustomers.Tables[0].Rows.Count - 1)
{
GenerateExcel(dt, @"C:\Users\dharmendra\Desktop\Excels\", "Test" + i);
dt.Clear();
}
}
}
private void GenerateExcel(DataTable dt, string filePath, string fileName)
{
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(dt, fileName);
wb.SaveAs(filePath + fileName + ".xlsx");
}
Screenshot
On Export button click the files are generated in the specified folder.