I have a 3-tier web application (database, app tier, web tier) written in MVC.
I want to generate Excel files at runtime using the data from the dat开发者_如何学运维abase.
My initial idea is to reference Excel Library in the web project and generate the file in the controller. I can stream it directly to the response and I can treat the file as a different view of the data. I already have a service method in place that returns the data from the database, as it is used on a page.
I am considering file generation on the app tier and then returning byte[]
to web tier. The argument here is that the file generation is part of business logic.
What would you do?
The excel output is actually a responsibility of the view, so you MUST do this in the controller. The model/app tier is responsible for data only, not the representation of it.
If you are using ASP.Net MVC you can declare an ExcelActionResult which takes in the view model and transforms it to a CSV/Excel output. Some related information:
Custom Excel Export Action
http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx
I agree, this is the right way to generate file at BLL(app tier). Check how we done with it in our project. It's little bit more complicated because our export/import model pluggable, but might it can have a sense for you.
First we have described 2 interfaces:
/// <summary>
/// Defines methods and properties for an import provider.
/// </summary>
public interface IImportProvider : IExtension
{
#region Methods
/// <summary>
/// Imports a data.
/// </summary>
/// <param name="data">The data to be imported.</param>
/// <param name="mimeType">The data MIME type.</param>
void Import(byte[] data, string mimeType);
#endregion
}
public interface IExportProvider : IExtension
{
#region Methods
/// <summary>
/// Exports a data.
/// </summary>
/// <param name="mimeType">Contains the data MIME type when this method returns.</param>
/// <returns>The exported date.</returns>
byte[] Export(ref string mimeType);
#endregion
}
We can implement these interfaces for any kind of import/export format. So, we process import/export data at BLL(app tier), and then, in case of export, we send it to Presentation Layer(web tier). Presentation layer resolves a file extensions by a MIME type and returns the File result:
return File(data, mimeType, String.Format("export.{0}", MimeTypeHelper.GetExtByMimeType(mimeType)));
This way, the presentation layer doesn't need to know what kind of import/export format has been used. All that required at the presentation layer to receive/send data from/to a user.
Depending on how much formatting is involved, I might create a Reporting Services (RS) report and use the RS web service to get the excel spreadsheet from data in the database.
精彩评论