locked
Cannot convert gridview to excel word or pdf. :( RRS feed

  • Question

  • User1049259259 posted

    Hi all,

    for converting grid to pdf,excel and word i am using following code on button click select:

    .cs file:(On Convert button click)

    if (DropDownList1.SelectedValue == "DOCX")
    {
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();

    }
    else if (DropDownList1.SelectedValue == "EXCEL")
    {

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    //Change the Header Row back to white color
    GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
    //Apply style to Individual Cells
    GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
    GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
    GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
    GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
    for (int i = 0; i < GridView1.Rows.Count;i++ )
    {
    GridViewRow row = GridView1.Rows[i];
    //Change Color back to white
    row.BackColor = System.Drawing.Color.White;
    //Apply text style to each Row
    row.Attributes.Add("class", "textmode");
    //Apply style to Individual Cells of Alternating Row
    if (i % 2 != 0)
    {row.Cells[0].Style.Add("background-color", "#C2D69B");
    row.Cells[1].Style.Add("background-color", "#C2D69B");
    row.Cells[2].Style.Add("background-color", "#C2D69B");
    row.Cells[3].Style.Add("background-color", "#C2D69B");
    }
    }
    GridView1.RenderControl(hw);
    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
    }


    }

    Problem is that the file which is being downloaded use to be in bytes and null data "AND THE OFFICE ASK ME TO CONVERT FOR ENCODING"


    plz help

    Wednesday, September 11, 2013 2:11 AM

Answers

  • User-718146471 posted
        protected void GenerateWord()
        {
            Response.Expires = 0;
            Response.Buffer = true;
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=\"report_" + DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss") + ".doc\"");
            Response.ContentType = "application/msword";
            Response.Write("<html>");
            Response.Write("<head>");
            Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
            Response.Write("<meta name=\"ProgId\" content=\"Word.Document\">");
            Response.Write("<meta name=\"Generator\" content=\"Microsoft Word 9\">");
            Response.Write("<meta name=\"Originator\" content=\"Microsoft Word 9\">");
            Response.Write("</head>");
    
            Response.Write("<body>");
            Response.Write(strBody.ToString());
            Response.Write("</div>");
            Response.Write("</body>");
            Response.Write("</html>");
            HttpContext.Current.Response.Flush();
            Response.End();
        }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:36 AM
  • User-718146471 posted

    For the PDF, this is what I use:

     

        private void GeneratePDF()
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL, 5, 5, 5, 5);
            iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.COURIER, 8);
            document.SetPageSize(iTextSharp.text.PageSize.LEGAL.Rotate());
            try
            {
                var output = new MemoryStream();
                PdfWriter.GetInstance(document, output);
                document.Open();
    
                WebClient wc = new WebClient();
                string htmlText = strBody.ToString();
                //Response.Write(htmlText);
    
                string[] separator = new string[] { @"<br clear='all' style='page-break-before:always'>" };
                string[] pages = htmlText.Split(separator, StringSplitOptions.None);
    
                foreach (string page in pages)
                {
                    document.NewPage();
                    List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
    
                    for (int k = 0; k < htmlarraylist.Count; k++)
                    {
                        document.Add((IElement)htmlarraylist[k]);
                    }
                }
                document.Close();
    
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Report-{0}.pdf", DateTime.Now.ToString("MM-dd-yyyy")));
                Response.BinaryWrite(output.ToArray());
            }
            catch
            {
            
            }
        }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:38 AM
  • User-718146471 posted

    And for the excel example, here is a link: http://forums.asp.net/post/2332406.aspx 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:39 AM

All replies

  • User-718146471 posted

    I'm going to compare what you have with my working code to see if you are missing something.

    Wednesday, September 11, 2013 7:33 AM
  • User-718146471 posted
        protected void GenerateWord()
        {
            Response.Expires = 0;
            Response.Buffer = true;
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=\"report_" + DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss") + ".doc\"");
            Response.ContentType = "application/msword";
            Response.Write("<html>");
            Response.Write("<head>");
            Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
            Response.Write("<meta name=\"ProgId\" content=\"Word.Document\">");
            Response.Write("<meta name=\"Generator\" content=\"Microsoft Word 9\">");
            Response.Write("<meta name=\"Originator\" content=\"Microsoft Word 9\">");
            Response.Write("</head>");
    
            Response.Write("<body>");
            Response.Write(strBody.ToString());
            Response.Write("</div>");
            Response.Write("</body>");
            Response.Write("</html>");
            HttpContext.Current.Response.Flush();
            Response.End();
        }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:36 AM
  • User-718146471 posted

    For the PDF, this is what I use:

     

        private void GeneratePDF()
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL, 5, 5, 5, 5);
            iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.COURIER, 8);
            document.SetPageSize(iTextSharp.text.PageSize.LEGAL.Rotate());
            try
            {
                var output = new MemoryStream();
                PdfWriter.GetInstance(document, output);
                document.Open();
    
                WebClient wc = new WebClient();
                string htmlText = strBody.ToString();
                //Response.Write(htmlText);
    
                string[] separator = new string[] { @"<br clear='all' style='page-break-before:always'>" };
                string[] pages = htmlText.Split(separator, StringSplitOptions.None);
    
                foreach (string page in pages)
                {
                    document.NewPage();
                    List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
    
                    for (int k = 0; k < htmlarraylist.Count; k++)
                    {
                        document.Add((IElement)htmlarraylist[k]);
                    }
                }
                document.Close();
    
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Report-{0}.pdf", DateTime.Now.ToString("MM-dd-yyyy")));
                Response.BinaryWrite(output.ToArray());
            }
            catch
            {
            
            }
        }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:38 AM
  • User-718146471 posted

    And for the excel example, here is a link: http://forums.asp.net/post/2332406.aspx 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2013 7:39 AM
  • User1049259259 posted

    Thanks , but i am not using itextsharp.....can u help without using itextsharp?

    Thursday, September 12, 2013 1:54 AM
  • User-718146471 posted

    Well you have to use something for the PDF because .net doesn't have a PDF builder built in. If there is a non-iTextSharp way to do this, I am all ears because that would be a great service to all .net programmers, not having to use iTextSharp but an actual native .net component from microsoft.

    Thursday, September 12, 2013 8:00 AM
  • User-46749029 posted

    Share a .NET component here, it can help you do this.

    Grid to PDF:

    Spire.DataExport.PDF.PDFExport PDFExport = new Spire.DataExport.PDF.PDFExport();
                PDFExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
                PDFExport.DataTable = this.GridView1.DataSource as DataTable;
                PDFExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
                PDFExport.PDFOptions.GridLineColor = Color.Green;
                PdfFont pdfFont=new PdfFont();
                pdfFont.Color=Color.Blue;
                PDFExport.PDFOptions.DataFont = pdfFont;
                PdfFont HpdfFont = new PdfFont();
                HpdfFont.Color = Color.Red;
                PDFExport.SaveToFile("ToPdf.pdf");

    Grid to Excel

          protected void Button1_Click(object sender, EventArgs e)
            {
    GridView1.DataSource = datatable;
     this.cellExport1.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView; this.cellExport1.DataFormats.CultureName = "zh-CN"; this.cellExport1.DataFormats.Currency = "¥#,###,##0.00"; this.cellExport1.DataFormats.DateTime = "yyyy-M-d H:mm"; this.cellExport1.DataFormats.Float = "#,###,##0.00"; this.cellExport1.DataFormats.Integer = "#,###,##0"; this.cellExport1.DataFormats.Time = "H:mm"; this.cellExport1.FileName = "ToExcel.xls";
    //....

    cellExport1.SaveToFile();
     }

    Grid to Word

                Spire.DataExport.RTF.RTFExport rtfExport = new Spire.DataExport.RTF.RTFExport();
                rtfExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
                rtfExport.DataTable = this.GridView1.DataSource as DataTable;
                rtfExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
                RTFStyle rtfStyle = new RTFStyle();
                rtfStyle.FontColor = Color.Blue;
                rtfStyle.BackgroundColor = Color.LightGreen;
                rtfExport.RTFOptions.DataStyle = rtfStyle;
                rtfExport.FileName="ToWord.doc";
                rtfExport.SaveToFile();


     

    Thursday, September 19, 2013 12:08 AM
  • User-718146471 posted

    Koohju, while your posting is appreciated, he wanted pdf inside .net which simply doesn't exist. This adds nothing more to the posting than the iTextSharp component I recommended. Not to mention, I believe that Spire is a paid-for component correct? This still doesn't satisfy his requirement for a native .NET PDF generator component built into the framework.

    http://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html#.UjsjznPD-Uk

    Thursday, September 19, 2013 12:19 PM