26 September, 2012

Export to .xls,.pdf,.doc and formatted .pdf from gridview using C# in ASP.NET

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

    protected void ASPNET_MSgBox(string L_Message)
    {
        string L_Script = "";
        L_Script = "<script> alert('" + L_Message + "');</script>";
        Page.RegisterClientScriptBlock("Information!!", L_Script);
    }
    private void loadData()
    {
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec Procedure 2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "dt");
                DataTable dt = ds.Tables["dt"];
                gvPVPFinal.DataSource = dt;               
                gvPVPFinal.DataBind();
            }
        }
        catch
        {
            ASPNET_MSgBox("ERROR: Approved Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToExcel()
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=Export.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        /*--------------Change GridView control under a Form------------------*/
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);
        /*--------------------------------*/
        //gvRegion.RenderControl(htmlWrite);
        Response.Write(stringWrite);
        Response.End();
    }
    private void ExportGridViewToFormatedPDF()
    {
        DataTable dt;
        try
        {
            string query = "";
            using (SqlConnection _SqlConnection = new SqlConnection(Global.connString))
            {
                _SqlConnection.Open();
                SqlCommand _SqlCommand = _SqlConnection.CreateCommand();
                query = @"Exec spPVPfinal '" + cmbTerritory.Text.ToString() + "',2";
                SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(query, _SqlConnection);
                DataSet ds = new DataSet();
                _SqlDataAdapter.Fill(ds, "PVPFianl");
                dt = ds.Tables["PVPFianl"];

                //Create a table
                iTextSharp.text.Table table = new iTextSharp.text.Table(GridView1.Columns.Count);
                table.Cellpadding = 5;
                //Set the column widths
                int[] widths = { 100, 250, 90, 50, 50, 380, 380 };

                for (int x = 0; x < GridView1.Columns.Count; x++)
                {
                    string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                    table.AddCell(cell);
                }
                table.SetWidths(widths);
                //Transfer rows from GridView to table
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        for (int j = 0; j < GridView1.Columns.Count; j++)
                        {
                            string cellText = Server.HtmlDecode(dt.Rows[i][j].ToString());
                            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
                            //Set Color of Alternating row
                            //if (i % 2 != 0)
                            //{
                            //    cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#C2D69B"));
                            //}                
                            table.AddCell(cell);
                        }
                    }
                }
                //Create the PDF Document
                Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                pdfDoc.Add(table);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
        catch
        {
            //ASPNET_MSgBox("ERROR: Download Priority Visit Planning (PVP).\\nContact with Administrator");
        }
    }
    private void ExportGridViewToPDF()
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 5f, 5f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
    private void ExportGridViewToWord()
    {
        Response.AddHeader("content-disposition", "attachment;filename=Export.doc");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";

        StringWriter stringWrite = new StringWriter();
        HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        HtmlForm frm = new HtmlForm();
        GridView1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(GridView1);
        frm.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());
        Response.End();
    }

 N.B.:
 add reference this dll : itextsharp.dll 
 please download .DLL from here : itextsharp.dll 

30 July, 2012

Export Data Table to Excel Using C#


        // TO USE:
        // 1) include COM reference to Microsoft Excel Object library
        // add namespace...
        // 2) using Excel = Microsoft.Office.Interop.Excel;
        private static void Excel_FromDataTable(DataTable dt)
        {
            // Create an Excel object and add workbook...
            Excel.ApplicationClass excel = new Excel.ApplicationClass();
            Excel.Workbook workbook = excel.Application.Workbooks.Add(true);    
            // true for object template???
            // Add column headings...
            int iCol = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                excel.Cells[1, iCol] = c.ColumnName;
            }
            // for each row of data...
            int iRow = 0;
            foreach (DataRow r in dt.Rows)
            {
                iRow++;
                // add each row's cell data...
                iCol = 0;
                foreach (DataColumn c in dt.Columns)
                {
                    iCol++;
                    excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
                }
            }
            // Global missing reference for objects we are not defining...
            object missing = System.Reflection.Missing.Value;
            // If wanting to Save the workbook...
            workbook.SaveAs("MyExcelWorkBook.xls",
            Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
            false, false, Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);
            // If wanting to make Excel visible and activate the worksheet...
            excel.Visible = true;
            Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
            ((Excel._Worksheet)worksheet).Activate();
            // If wanting excel to shutdown...
            ((Excel._Application)excel).Quit();
        }

08 July, 2012

Simple File Upload using FTP and C#.NET

using System.Net;
using System.IO;

private void UploadToFTP(string filename)
{
    try
    {
       FileInfo fileInf = new FileInfo(filename);
       string uri = ftpAddress + fileInf.Name;
       FtpWebRequest reqFTP;
       // Create FtpWebRequest object from the Uri provided
 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpAddress
+ fileInf.Name));
       // Provide the WebPermission Credintials
       reqFTP.Credentials = new NetworkCredential(ftpUser,ftpPassword);
       // By default KeepAlive is true, where the control connection is
       // not closed after a command is executed.
       reqFTP.KeepAlive = false;
       // Specify the command to be executed.
       reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
       // Specify the data transfer type.
       reqFTP.UseBinary = true;
       // Notify the server about the size of the uploaded file
       reqFTP.ContentLength = fileInf.Length;
       // The buffer size is set to 2kb
       int buffLength = 2048;
       byte[] buff = new byte[buffLength];
       int contentLen;
       // Opens a file stream (System.IO.FileStream) to read
       //the file to be uploaded
       FileStream fs = fileInf.OpenRead();
       try
       {
          // Stream to which the file to be upload is written
          Stream strm = reqFTP.GetRequestStream();
          // Read from the file stream 2kb at a time
          contentLen = fs.Read(buff, 0, buffLength);
          // Till Stream content ends
          while (contentLen != 0)
          {
               // Write Content from the file stream to the
               // FTP Upload Stream
               strm.Write(buff, 0, contentLen);
               contentLen = fs.Read(buff, 0, buffLength);
          }
          // Close the file stream and the Request Stream
          strm.Close();
          fs.Close();
       }
       catch (Exception ex)
       {
            //MessageBox.Show(ex.Message, "FTP File Upload Error");
            throw new Exception(ex.Message);
       }
    }
    catch (Exception ex)
    {
      //MessageBox.Show(ex.Message, "FTP File Upload Error");
      throw new Exception(ex.Message);
    }
 }



N.B.: Make sure that u have proper permission to create file in FTP. 
address like: ftp://1.1.1.1/fileFolder/