Exemplo n.º 1
0
    private void GernerateProductCSV()
    {
        DataSet dsProduct = new DataSet();

        try
        {
            dsProduct = objproduct.SelectProductDetailForGenerateCSV();

            if (dsProduct.Tables[0].Rows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();

                //For i As Integer = 0 To dsProduct.Tables(0).Columns.Count - 1
                //    If i = dsProduct.Tables(0).Columns.Count - 1 Then
                //        sb.Append(dsProduct.Tables(0).Columns(i).ColumnName)
                //    Else
                //        sb.Append(dsProduct.Tables(0).Columns(i).ColumnName + ",")
                //    End If

                //Next
                string strheade = "";
                strheade = "productId,productName,productDescription,sku,barcode,isVarientProduct,isMasterProduct,price,cost,minimumQuantity,inventory,isActive,isFeatured";
                sb.Append(strheade);
                sb.Append(Environment.NewLine);

                for (int j = 0; j <= dsProduct.Tables[0].Rows.Count - 1; j++)
                {
                    for (int k = 0; k <= dsProduct.Tables[0].Columns.Count - 1; k++)
                    {
                        if (k == dsProduct.Tables[0].Columns.Count - 1)
                        {
                            sb.Append(dsProduct.Tables[0].Rows[j][k].ToString());
                        }
                        else
                        {
                            if (dsProduct.Tables[0].Rows[j][k].ToString().Contains(","))
                            {
                                sb.Append("\"" + dsProduct.Tables[0].Rows[j][k].ToString() + "\",");
                            }
                            else
                            {
                                sb.Append(dsProduct.Tables[0].Rows[j][k].ToString() + ",");
                            }
                            //sb.Append(dsProduct.Tables[0].Rows[j][k].ToString() + ",");
                        }
                    }
                    sb.Append(Environment.NewLine);
                }

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "text/csv";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=ProductCSV.csv");
                HttpContext.Current.Response.AddHeader("Content-Length", sb.Length.ToString());
                HttpContext.Current.Response.AddHeader("Pragma", "public");
                HttpContext.Current.Response.Write(sb.ToString());
                HttpContext.Current.Response.End();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally { dsProduct.Dispose(); }
    }