Export to Excel, How to fit the column width

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
13 years ago
Hi ,

I have a question. Just like my topic.

When I Enter administration page , i click "Catalog" - > "Products" -> "Manage Products", and i want to make "Export to Excel" , here is the question for me. How to make the column width of excel file that i export?
I found the source code "Administration\Modules\Products.ascx.cs" just below:


        protected void btnExportXLS_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string fileName = string.Format("products_{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
                    string filePath = string.Format("{0}files\\ExportImport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
                    ProductCollection products = GetProducts(0);

                    ExportManager.ExportProductsToXls(filePath, products);
                    CommonHelper.WriteResponseXls(filePath, fileName);
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }


I don't know should i use ExcelHelper class (select row ExportManager.ExportProductsToXls(filePath, products);
and press keyboard F12, you will see the method in ExcelHelper class ) to make my change. Or i should use method just like below? Need to use datasource binding control (like datagrid or gridview ). Any help for me?Thanks!


public void ToExcel(System.Web.UI.Control ctl)  
  {

   HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
   HttpContext.Current.Response.Charset ="UTF-8";    
   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
   HttpContext.Current.Response.ContentType ="application/ms-excel";
   //image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword

   ctl.Page.EnableViewState =false;    
   System.IO.StringWriter  tw = new System.IO.StringWriter() ;
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
   ctl.RenderControl(hw);
   HttpContext.Current.Response.Write(tw.ToString());
   HttpContext.Current.Response.End();

  }


13 years ago
Any thoughs help me? Please just give a link or a way.

Thanks
13 years ago
Hi everyone,

i found a way to slove my question. Just use one xls file to make a  templete. And then comment the source code (in Libraries\Nop.BusinessLogic\ExportImport\ExportManager.cs) where make a table. Just below method:


        public static void ExportProductsToXls(string filePath, ProductCollection products)
        {
            using (ExcelHelper excelHelper = new ExcelHelper(filePath))
            {
                excelHelper.Hdr = "YES";
                excelHelper.Imex = "0";


                Dictionary<string, string> tableDefinition = new Dictionary<string, string>();

                int maxStringLength = 200;
                //tableDefinition.Add("ID", "int");
                //tableDefinition.Add("Name", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("ShortDescription", string.Format("nvarchar({0})", maxStringLength));

                //tableDefinition.Add("FullDescription", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("ProductTypeId", "int");
                //tableDefinition.Add("TemplateId", "int");
                //tableDefinition.Add("ShowOnHomePage", "nvarchar(5)");
                //tableDefinition.Add("MetaKeywords", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("MetaDescription", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("MetaTitle", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("AllowCustomerReviews", "nvarchar(5)");
                //tableDefinition.Add("AllowCustomerRatings", "nvarchar(5)");
                //tableDefinition.Add("Published", "nvarchar(5)");
                //tableDefinition.Add("SKU", string.Format("nvarchar(200)", maxStringLength));
                //tableDefinition.Add("ManufacturerPartNumber", string.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("IsGiftCard", "nvarchar(5)");
                //tableDefinition.Add("IsDownload", "nvarchar(5)");
                //tableDefinition.Add("DownloadId", "int");
                //tableDefinition.Add("UnlimitedDownloads", "nvarchar(5)");
                //tableDefinition.Add("MaxNumberOfDownloads", "int");
                //tableDefinition.Add("DownloadActivationType", "int");
                //tableDefinition.Add("HasSampleDownload", "nvarchar(5)");
                //tableDefinition.Add("SampleDownloadId", "int");
                //tableDefinition.Add("HasUserAgreement", "nvarchar(5)");
                //tableDefinition.Add("UserAgreementText", String.Format("nvarchar({0})", maxStringLength));
                //tableDefinition.Add("IsRecurring", "nvarchar(5)");
                //tableDefinition.Add("CycleLength", "int");
                //tableDefinition.Add("CyclePeriod", "int");
                //tableDefinition.Add("TotalCycles", "int");
                //tableDefinition.Add("IsShipEnabled", "nvarchar(5)");
                //tableDefinition.Add("IsFreeShipping", "nvarchar(5)");
                //tableDefinition.Add("AdditionalShippingCharge", "decimal");
                //tableDefinition.Add("IsTaxExempt", "nvarchar(5)");
                //tableDefinition.Add("TaxCategoryId", "int");
                //tableDefinition.Add("ManageInventory", "int");
                //tableDefinition.Add("StockQuantity", "int");
                //tableDefinition.Add("DisplayStockAvailability", "nvarchar(5)");
                //tableDefinition.Add("MinStockQuantity", "int");
                //tableDefinition.Add("LowStockActivityId", "int");

                //tableDefinition.Add("ProductCode", string.Format("nvarchar({0})", maxStringLength));

                //tableDefinition.Add("AllowOutOfStockOrders", "nvarchar(5)");
                //tableDefinition.Add("OrderMinimumQuantity", "int");
                //tableDefinition.Add("OrderMaximumQuantity", "int");
                //tableDefinition.Add("DisableBuyButton", "nvarchar(5)");

                //tableDefinition.Add("Price", "decimal");

                //tableDefinition.Add("OldPrice", "decimal");
                //tableDefinition.Add("ProductCost", "decimal");
                //tableDefinition.Add("CustomerEntersPrice", "nvarchar(5)");
                //tableDefinition.Add("MinimumCustomerEnteredPrice", "decimal");
                //tableDefinition.Add("MaximumCustomerEnteredPrice", "decimal");
                //tableDefinition.Add("Weight", "decimal");
                //tableDefinition.Add("Length", "decimal");
                //tableDefinition.Add("Width", "decimal");
                //tableDefinition.Add("Height", "decimal");
                //tableDefinition.Add("CreatedOn", "decimal");

                //excelHelper.WriteTable("Products", tableDefinition);

       ...............................................Other source just the same
                }
          }


Because i have made a templete just contain the Products table. And i also change the width for  all column and make the xls templete file to auto newline.So now the content will fix width as i want.

Because all the export file have only one , use time name to seprate. And i copy templete xls file and give  only name for the export file just like before(just like :products_2011-02-13-00-00-07_4290.xls) which the source code in NopCommerceStore\Administration\Modules\Products.ascx.cs


      protected void btnExportXLS_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    string fileName = string.Format("products_{0}_{1}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"), CommonHelper.GenerateRandomDigitCode(4));
                    string templateName = "products.xls";  

/*first you should create a new template file  in NopCommerceStore\files\ExportImport and name products.xls
products.xls file just the table [products] info. And you can fix the width for that as you want*/

*/


                    string filePath = string.Format("{0}files\\ExportImport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, fileName);
                    string templeteFilePath = string.Format("{0}files\\ExportImport\\{1}", HttpContext.Current.Request.PhysicalApplicationPath, templateName);
                    //Here should let the templete file use for everytime you want to export, so need to copy a new xls file to insert data
                    File.Copy(templeteFilePath, filePath, true);
                    ProductCollection products = GetProducts(0);

                    ExportManager.ExportProductsToXls(filePath, products);
                    CommonHelper.WriteResponseXls(filePath, fileName);
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }


It can really work , just can create a new excel in NopCommerceStore\files\ExportImport, and the width just as the templete. But here have another question,  i cannot use browser to open that. and also download. When i select "Open" or "download" ,it just let me download products.aspx page. I don't why.

Any thoughs help me?
Thanks!
13 years ago
Hi ,

I don't know why. Now i can export excel file as i want. But when i debug , i catch exception.
When i use the administration to view log info, i see the message named "File does not exist. "
And exception is below:

System.Web.HttpException (0x80004005): File does not exist. at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response) at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String overrideVirtualPath) at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)


It just show when i debug to :
response.End();

It is in the method of the last line:

        /// <summary>
        /// Write XLS file to response
        /// </summary>
        /// <param name="filePath">File path</param>
        /// <param name="targetFileName">Target file name</param>
        public static void WriteResponseXls(string filePath, string targetFileName)
        {
            if (!String.IsNullOrEmpty(filePath))
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.Charset = "utf-8";
                response.ContentType = "text/xls";
                response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName));
                response.BinaryWrite(File.ReadAllBytes(filePath));
                response.End();
            }
        }

Although it works well, i just want to know why it apprears.
Thanks,csdbfans
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.