Per generare un report in formato excel con Visual Studio e il Framework 3.5 bastano questi semplici passi:
  • Generare un dataset tipizzato DsTestReport.xsd
  • Creare un report Report1.rdlc
  • Creare una pagina Report.aspx per inviare al browser il report

Ecco i file del progetto:

XML: DsTestReport.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="DsTestReport" targetNamespace="http://tempuri.org/DsTestReport.xsd" xmlns:mstns="http://tempuri.org/DsTestReport.xsd" xmlns="http://tempuri.org/DsTestReport.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:annotation>
    <xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
      <DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
        <Connections />
        <Tables />
        <Sources />
      </DataSource>
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="DsTestReport" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:EnableTableAdapterManager="true" msprop:Generator_DataSetName="DsTestReport" msprop:Generator_UserDSName="DsTestReport">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="TblTest" msprop:Generator_TableClassName="TblTestDataTable" msprop:Generator_TableVarName="tableTblTest" msprop:Generator_TablePropName="TblTest" msprop:Generator_RowDeletingName="TblTestRowDeleting" msprop:Generator_UserTableName="TblTest" msprop:Generator_RowChangingName="TblTestRowChanging" msprop:Generator_RowEvHandlerName="TblTestRowChangeEventHandler" msprop:Generator_RowDeletedName="TblTestRowDeleted" msprop:Generator_RowEvArgName="TblTestRowChangeEvent" msprop:Generator_RowChangedName="TblTestRowChanged" msprop:Generator_RowClassName="TblTestRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Description" msprop:Generator_ColumnVarNameInTable="columnDescription" msprop:Generator_ColumnPropNameInRow="Description" msprop:Generator_ColumnPropNameInTable="DescriptionColumn" msprop:Generator_UserColumnName="Description" type="xs:string" minOccurs="0" />
              <xs:element name="Date" msprop:Generator_ColumnVarNameInTable="columnDate" msprop:Generator_ColumnPropNameInRow="Date" msprop:Generator_ColumnPropNameInTable="DateColumn" msprop:Generator_UserColumnName="Date" type="xs:dateTime" minOccurs="0" />
              <xs:element name="Number" msprop:Generator_ColumnVarNameInTable="columnNumber" msprop:Generator_ColumnPropNameInRow="Number" msprop:Generator_ColumnPropNameInTable="NumberColumn" msprop:Generator_UserColumnName="Number" type="xs:decimal" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>
questo è un dataset (DsTestReport) con una tabella (TblTest) che ha tre campi:
  • Description di tipo string
  • Date di tipo DateTime
  • Number di tipo Decimal

XML: Report1.rdlc

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
  <DataSources>
    <DataSource Name="DsTestReport">
      <ConnectionProperties>
        <DataProvider>System.Data.DataSet</DataProvider>
        <ConnectString>/* Local Connection */</ConnectString>
      </ConnectionProperties>
      <rd:DataSourceID>69c05f3a-2bfc-4359-b136-600d72d6488b</rd:DataSourceID>
    </DataSource>
  </DataSources>
  <DataSets>
    <DataSet Name="TblTest">
      <Fields>
        <Field Name="Description">
          <DataField>Description</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="Date">
          <DataField>Date</DataField>
          <rd:TypeName>System.DateTime</rd:TypeName>
        </Field>
        <Field Name="Number">
          <DataField>Number</DataField>
          <rd:TypeName>System.Decimal</rd:TypeName>
        </Field>
      </Fields>
      <Query>
        <DataSourceName>DsTestReport</DataSourceName>
        <CommandText>/* Local Query */</CommandText>
      </Query>
      <rd:DataSetInfo>
        <rd:DataSetName>TblTest</rd:DataSetName>
        <rd:SchemaPath>C:\Users\AlbertoB\documents\visual studio 2010\Projects\WebApplication1\WebApplication1\DsTestReport.xsd</rd:SchemaPath>
        <rd:TableName>TblTest</rd:TableName>
        <rd:TableAdapterFillMethod />
        <rd:TableAdapterGetDataMethod />
        <rd:TableAdapterName />
      </rd:DataSetInfo>
    </DataSet>
  </DataSets>
  <Body>
    <ReportItems>
      <Tablix Name="Tablix1">
        <TablixBody>
          <TablixColumns>
            <TablixColumn>
              <Width>2.80717in</Width>
            </TablixColumn>
            <TablixColumn>
              <Width>0.98425in</Width>
            </TablixColumn>
            <TablixColumn>
              <Width>0.98425in</Width>
            </TablixColumn>
          </TablixColumns>
          <TablixRows>
            <TablixRow>
              <Height>0.23622in</Height>
              <TablixCells>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Textbox2">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>Description</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontWeight>Bold</FontWeight>
                                <Color>White</Color>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Textbox2</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#622424</Color>
                          <Style>Solid</Style>
                        </Border>
                        <BackgroundColor>#4e0000</BackgroundColor>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Textbox3">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>Date</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontWeight>Bold</FontWeight>
                                <Color>White</Color>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Textbox3</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#622424</Color>
                          <Style>Solid</Style>
                        </Border>
                        <BackgroundColor>#4e0000</BackgroundColor>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Textbox5">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>Number</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontWeight>Bold</FontWeight>
                                <Color>White</Color>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Textbox5</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#622424</Color>
                          <Style>Solid</Style>
                        </Border>
                        <BackgroundColor>#4e0000</BackgroundColor>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
              </TablixCells>
            </TablixRow>
            <TablixRow>
              <Height>0.23622in</Height>
              <TablixCells>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Description">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>=Fields!Description.Value</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontSize>9pt</FontSize>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Description</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#e5e5e5</Color>
                          <Style>Solid</Style>
                        </Border>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Date">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>=Fields!Date.Value</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontSize>9pt</FontSize>
                                <Format>d</Format>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Date</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#e5e5e5</Color>
                          <Style>Solid</Style>
                        </Border>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
                <TablixCell>
                  <CellContents>
                    <Textbox Name="Number">
                      <CanGrow>true</CanGrow>
                      <KeepTogether>true</KeepTogether>
                      <Paragraphs>
                        <Paragraph>
                          <TextRuns>
                            <TextRun>
                              <Value>=Fields!Number.Value</Value>
                              <Style>
                                <FontFamily>Verdana</FontFamily>
                                <FontSize>9pt</FontSize>
                                <Format>#,##0.00</Format>
                              </Style>
                            </TextRun>
                          </TextRuns>
                          <Style />
                        </Paragraph>
                      </Paragraphs>
                      <rd:DefaultName>Number</rd:DefaultName>
                      <Style>
                        <Border>
                          <Color>#e5e5e5</Color>
                          <Style>Solid</Style>
                        </Border>
                        <PaddingLeft>2pt</PaddingLeft>
                        <PaddingRight>2pt</PaddingRight>
                        <PaddingTop>2pt</PaddingTop>
                        <PaddingBottom>2pt</PaddingBottom>
                      </Style>
                    </Textbox>
                  </CellContents>
                </TablixCell>
              </TablixCells>
            </TablixRow>
          </TablixRows>
        </TablixBody>
        <TablixColumnHierarchy>
          <TablixMembers>
            <TablixMember />
            <TablixMember />
            <TablixMember />
          </TablixMembers>
        </TablixColumnHierarchy>
        <TablixRowHierarchy>
          <TablixMembers>
            <TablixMember>
              <KeepWithGroup>After</KeepWithGroup>
            </TablixMember>
            <TablixMember>
              <Group Name="Details" />
            </TablixMember>
          </TablixMembers>
        </TablixRowHierarchy>
        <DataSetName>TblTest</DataSetName>
        <Height>1.2cm</Height>
        <Width>12.13021cm</Width>
        <Style>
          <Border>
            <Style>None</Style>
          </Border>
        </Style>
      </Tablix>
    </ReportItems>
    <Height>2cm</Height>
    <Style />
  </Body>
  <Width>13cm</Width>
  <Page>
    <PageHeight>29.7cm</PageHeight>
    <PageWidth>21cm</PageWidth>
    <LeftMargin>0.5cm</LeftMargin>
    <RightMargin>0.5cm</RightMargin>
    <TopMargin>0.5cm</TopMargin>
    <BottomMargin>0.5cm</BottomMargin>
    <ColumnSpacing>0.13cm</ColumnSpacing>
    <Style />
  </Page>
  <Language>it-IT</Language>
  <rd:ReportID>9d18c296-7325-437d-84c1-94303b537200</rd:ReportID>
  <rd:ReportUnitType>Cm</rd:ReportUnitType>
</Report>
il report che utilizza il dataset e visualizza una tabella

C#: Report.aspx

namespace SgartWebApplicationReport
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
        //i dati da passare al report
        DataTable tbl = GetDatasetTest();
        //invio il report al browser
        RenderReport("Report1.rdlc", tbl, "ReportDiProva");
    }

    private DataTable GetDatasetTest()
    {
      DsTestReport ds = new DsTestReport();
      DsTestReport.TblTestDataTable tbl =  ds.TblTest;
      
      DsTestReport.TblTestRow row = null;

      row = tbl.NewTblTestRow();
      row.Description = "Generare dataset";
      row.Date = new DateTime(2012, 2,22);
      row.Number = 20.4m;
      tbl.Rows.Add(row);

      row = tbl.NewTblTestRow();
      row.Description = "Creare report rdlc";
      row.Date = new DateTime(2012, 2, 23);
      row.Number = 14560.78m;
      tbl.Rows.Add(row);

      row = tbl.NewTblTestRow();
      row.Description = "Creare pagina aspx/ashx ";
      row.Date = new DateTime(2012, 11, 24);
      row.Number = 360.56m;
      tbl.Rows.Add(row);

      return ds.TblTest;
    
    }
 
     /// <summary>
    /// Microsoft.ReportViewer.Common.dll
    /// Microsoft.ReportViewer.WebForms.dll
    /// </summary>
    /// <param name="reportName"></param>
    /// <param name="dt"></param>
    /// <param name="fileName"></param>
    private void RenderReport(string reportName, DataTable dt, string fileName)
    {
      LocalReport localReport = new LocalReport();
      localReport.ReportPath = Server.MapPath(reportName);

      //dt.TableName: deve coincidere con il nome del dataset definito nel report (rd:DataSetName)
      ReportDataSource reportDataSource = new ReportDataSource(dt.TableName, dt);
      localReport.DataSources.Add(reportDataSource);

       // se si hanno delle eccezioni di security può essere necessario inserire queste righe
       // soprattutto se il report gira all'interno di SharePoint 
       // In alternativa impostare il trust nel web.config a Full
       // Assembly myAssembly = Assembly.GetExecutingAssembly();
       // localReport.ExecuteReportInCurrentAppDomain(myAssembly.Evidence);
       // localReport.AddTrustedCodeModuleInCurrentAppDomain(myAssembly.FullName);

      string reportType = "EXCEL";
      string mimeType;
      string encoding;
      string fileNameExtension;

      //The DeviceInfo settings should be changed based on the reportType
      //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
      string deviceInfo =
      "<DeviceInfo>" +
      "  <OutputFormat>EXCEL</OutputFormat>" +
      "  <PageWidth>21cm</PageWidth>" +
      "  <PageHeight>29.7cm</PageHeight>" +
      "  <MarginTop>0.5cm</MarginTop>" +
      "  <MarginLeft>0.5cm</MarginLeft>" +
      "  <MarginRight>0.5cm</MarginRight>" +
      "  <MarginBottom>0.5cm</MarginBottom>" +
      "</DeviceInfo>";
      Warning[] warnings;
      string[] streams;
      byte[] renderedBytes;

      //Render the report
      renderedBytes = localReport.Render(
          reportType,
          deviceInfo,
          out mimeType,
          out encoding,
          out fileNameExtension,
          out streams,
          out warnings);

      Response.Clear();
      Response.ContentType = mimeType;
      Response.AddHeader("content-disposition", "inline; filename=" + fileName + "." + fileNameExtension);
      Response.BinaryWrite(renderedBytes);
      Response.End();
    }
  }
}
la pagina che crea i dati da passare al report e rispedisce il file al browser. Viene restituito un file excel con tre colonne, una in formato stringa, una in formato data formattata in italiano e l'ultima in formato decimale.
Il nome della tabella definita nel dataset (TblTest) deve concidere con il nome assegnato nel report.
Ricordati di inserire le reference alle dll Microsoft.ReportViewer.Common.dll e Microsoft.ReportViewer.WebForms.dll DLL per ReportViewer
Tags:
ASP.NET54 C#237 .NET66 Esempi225 Excel11 Reporting16 Reporting Services18
Potrebbe interessarti anche: