Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Open Visual Studio and create a .NET project.
    • The sample code uses a web application.
  2. Add a reference to SoftArtisans.OfficeWriter.ExcelWriter.dll
    • SoftArtisans.OfficeWriter.ExcelWriter.dll is located under Program Files > SoftArtisans > OfficeWriter > dotnet > bin

Writing the Code

...

Merging template together with CopySheet

1. Include the SoftArtisans.OfficeWriter.ExcelWriter namespace in the code behind

Code Block
using SoftArtisans.OfficeWriter.ExcelWriter;

2. Globally declare the ExcelTemplate  and ExcelApplication objects. We are also using a MemoryStream to pass the application object to the template object., ExcelApplication, and Workbook objects.

Code Block
MemoryStream
stream;
ExcelApplication XLA;
ExcelTemplate XLT;
Workbook 

The next step uses CopySheet to create a JoinReports method.

Joining Reports

...

MERGEDWB;

3. Define a method that will open the two template files and merge them together with CopySheet. In this case, the method is called MergeTemplates().

Code Block

protected void MergeTemplates()
{

}

4. In MergeTemplates(), instantiate the ExcelApplication object.

Code Block
XLA = new ExcelApplication();

25. Open the workbook to copy into.that the worksheets will be copied into. For this example, the second template will be copied into the first template workbook.

Code Block
WorkbookMERGEDWB wbTo = XLA.Open(Page.MapPath("//templates//Part1_Financial_Template.xlsx"));

36. Open the workbook to copy fromsecond workbook that will be merged into the first.

Code Block
Workbook wbFromwbOther = XLA.Open(Page.MapPath("//templates//Part2_Financial_Template.xlsx"));

47. Open Copy the worksheets to copy from. These are the first sheet with a table, and the second sheet containing the data.

Code Block

Worksheet wsFrom = wbFrom[0];
Worksheet wsFromData = wbFrom[1];

5. Call CopySheet for each worksheet. The data sheet needs to be copied first so that the references to it remain validworksheet from the second template into the first workbook. Worksheet.Name can be used to pass along the original name of the worksheet ("Percent by Quarter"). The worksheet should be copied to the end of the current worksheet collection (index 1).

Code Block
wbToMERGEDWB.Worksheets.CopySheet(wsFromDatawbOther[0], 1, "Data");
wbTo.Worksheets.CopySheet(wsFrom, 1, "Percent by Quarter"wbOther[0].Name);

6. Instantiate the MemoryStream. ExcelTemplate opens ExcelApplication objects as streams

Code Block

stream = new MemoryStream();

7. Finally save the joined file to a stream.

Code Block

XLA.Save(wbTo, stream);

Data Binding

Binding Data to the Merged Template

1. Create a method to bind handle binding and process the two templates. This method takes the filename and returns the processed template objectprocessing the data import for the combined template. For this example, the method is called BindDataToMergedTemplate().

Code Block
private
protected void BindTemplateDataBindDataToMergedTemplate()
{

}

4. In the BindTemplateData method, instantiate the  ExcelTemplate object2. Instantiate ExcelTemplate and open the template file with ExcelTemplate.Open(ExcelApplication, Workbook) to open directly from the pre-existing ExcelApplication instance.

Code Block

XLT = new ExcelTemplate();

5. Open the template files with the ExcelTemplate.Open method. This opens the stream created in the JoinReports method

Code Block

XLT.Open(stream);

6. Create a DataBindingProperties object. None of the binding properties will be changed for this tutorial, but DataBindingProperties is a required parameter in ExcelTemplate data binding methods.

Code Block
DataBindingProperties dataProps = XLT.CreateDataBindingProperties();

7. Get the data for Assets, Losses, and Other.

Info
titleFollowing the Sample

In the sample project, we are parsing CSV files with query results, rather than querying a live database. The CSV files are available under the data directory. There is a copy of the CSV parser, GenericParsing.dll in the bin directory of the project GetCSVData is defined in Part1.aspx.cs in a region marked Utility Methods.

These calls are to a helper method GetCSVData that parses the CSV files and returns a DataTable with the values.

If you are following in your own project and would like to parse the CSV files as well, you will need to:

  • Add a reference to GenericParsing.dll
  • Include GeneringParsing at the top of your code.
  • Add the GetCSVData method that can be found in the sample code.
Code Block

DataTable dtAssets = GetCSVData("//data//Assets.csv");
DataTable dtLosses = GetCSVData("//data//Losses.csv");
DataTable dtOther = GetCSVData("//data//Other.csv");

8. Create the datasets for the header row in template 1. This will simply be ignored by template 2.

Code Block
XLA, MERGEDWB);

3. Use the code from Part 1 and Part 2 to bind data to the template. Note that both templates used the same data set, so the calls to bind the data only need to be made once.

Info

If there are duplicate data markers in a workbook, ExcelWriter will import the matching data to all the data markers, across all the worksheets in the workbook.

Code Block

//Create data binding properties for ExcelTemplate
DataBindingProperties bindingProps = XLT.CreateDataBindingProperties();

//Create the array of header values. This example only binds a single item
string[] headerValues = { "2011" };

//Create the array of header names.
string[] headerNames = { "FiscalYear" };

9. Use ExcelTemplate.BindData to bind the data for the Top and Details Sales data sets.

Code Block

XLT.BindData(dtAssets, "Assets", bindingProps);
XLT.BindData(dtLosses, "Losses", bindingProps);
XLT.BindData(dtOther, "Other", bindingProps);

10. Use the ExcelTemplate.BindRowData method to bind the header data to the data markers in the template file (i.e. %%=Header.FiscalYear).

Code Block

//Get the datatables to be bound into the template.
//This example uses CSV data, but the data can come from
//anywhere
DataTable dtAssets = GetCSVData("//data//Assets.csv");
DataTable dtLosses = GetCSVData("//data//Losses.csv");
DataTable dtOther = GetCSVData("//data//Other.csv");

//Bind the header row data
XLT.BindRowData(headerValues, headerNames, "Header", bindingProps);

11. Call ExcelTemplate.Process() to import all data into the file.

Code Block

XLT.Process();

Do not save the file. In the next step the XLT object will be post processed by ExcelApplication

Post-Processing

1. The file has to be post-processed with autofit. This is also the workbook that is being copied to. Instantiate the ExcelApplication object:

Code Block

XLA = new ExcelApplication();

2. Open the populated template file with ExcelApplication. The file will open as a Workbook object.

Code Block

Workbook wb = XLA.Open(XLT);

3. Access the first Worksheet.

Code Block

Worksheet ws = wb.Worksheets[0];

4. Call Area.AutoFitHeight() and Area.AutoFitWidth() to set the column and row height. AutoFitWidth sets the column width to fit the widest populated cell in the column. AutoFitHeight sets the row height to highest populated cell in the row. In this snippet, the area is Worksheet.PopulatedCells, which returns an area containing all populated cells.

Code Block

ws.PopulatedCells.AutoFitWidth();
ws.PopulatedCells.AutoFitWidth();

5. Finally, call ExcelApplication.Save to save the final file. This example streams the file using the page response.

Code Block

XLA.Save(wb, Page.Response, "temp
//Bind the datatables
XLT.BindData(dtAssets, "Assets", bindingProps);
XLT.BindData(dtLosses, "Losses", bindingProps);
XLT.BindData(dtOther, "Other", bindingProps);

//Process to import the data to the file
XLT.Process();

XLT.Save(Page.Response, "Part3_Output.xlsx", false);

Final Code

Code Block
using SoftArtisans.OfficeWriter.ExcelWriter;
using GenericParsing; //See Part 1 for more information about the CSV parser
...
//Declare globals
 MemoryStream stream;
 ExcelApplication XLA;
 ExcelTemplate XLT;
 Workbook MERGEDWB;

//Merges the reports and binds data to the templates
protected void RunReport()
{
          //Join the two reports using CopySheet
          JoinReportsMergeTemplates();

          //bind the data for the newly modified file
          BindTemplateDataBindDataToMergedTemplate();

}


protected void JoinReports()
{
	//Instantiate ExcelApplication
	XLA = new ExcelApplication();

	//FinallyOpen postprocessthe tofirst set the auto fit values
     template
	MERGEDWB = XLA.Open(Page.MapPath("//templates//Part1_Financial_Template.xlsx"));

	//Open the second template
	Workbook wbOther = XLA.Open(Page.MapPath("//templates//Part2_Financial_Template.xlsx"));

	//Call CopySheet
    PostprocessTemplate(    MERGEDWB.Worksheets.CopySheet(wbOther[0], 1, wbOther[0].Name);

}

protected void BindTemplateData()
{
	XLT = new ExcelTemplate();

	//Open the template file
	XLT.Open(streamXLA, MERGEDWB);

	//Create data binding properties for ExcelTemplate
	DataBindingProperties bindingProps = XLT.CreateDataBindingProperties(); 

	//Get the datatables to be bound into the template.
	//This example uses CSV data, but the data can come from
	//anywhere
	DataTable dtAssets = GetCSVData("//data//Assets.csv");
	DataTable dtLosses = GetCSVData("//data//Losses.csv");
	DataTable dtOther = GetCSVData("//data//Other.csv");

	//Bind the datatables
	XLT.BindData(dtAssets, "Assets", bindingProps);
	XLT.BindData(dtLosses, "Losses", bindingProps);
	XLT.BindData(dtOther, "Other", bindingProps);

	/*This section only applies to the first template. It will be ignored by the 
	second template, since there are no markers to bind to.*/

	//Create the array of header values. This example only binds a single item
	string[] headerValues = { "2011" };

	//Create the array of header names.
	string[] headerNames = { "FiscalYear" };

	//Bind the header row data
	XLT.BindRowData(headerValues, headerNames, "Header", bindingProps);

	//end

	//Process to import the data to the file
	XLT.Process();
}
 protected void JoinReports() { 	//Instantiate ExcelApplication 	XLA = new ExcelApplication();

	//Open the first template
	Workbook wbTo = XLA.Open(Page.MapPath("//templates//Part1_Financial_Template.xlsx"));

	//Open the second template
	Workbook wbFrom = XLA.Open(Page.MapPath("//templates//Part2_Financial_Template.xlsx"));

	//Open the first worksheet, with the table
	Worksheet wsFrom = wbFrom[0];
	//Open the second worksheet, with the data
	Worksheet wsFromData = wbFrom[1];

	//Call CopySheet, making sure to copy the data sheet first
	wbTo.Worksheets.CopySheet(wsFromData, 1, "Data");
	wbTo.Worksheets.CopySheet(wsFrom, 1, "Percent by Quarter");

	//Instantiate the stream to save to
        stream = new MemoryStream();

        //Save the stream
        XLA.Save(wbTo, stream);
}

protected void PostprocessTemplate()
{
         //Instantiate ExcelApplication
         XLA = new ExcelApplication();

         //Open the newly populated XLT
         Workbook wb = XLA.Open(XLT);

         //Get the first worksheet
         Worksheet ws = wb.Worksheets[0];

         //Set autofit for the width and height
         //This sets all cells to the highest or widest
         //value present in the area
         ws.PopulatedCells.AutoFitWidth();
         ws.PopulatedCells.AutoFitHeight();

         //Open the processed file in your browser
         XLA.Save(wb, Page.Response, "Part3_Output.xlsx", false);
}


Downloads

You can download the code for the Financial Report here.

...