Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Sunday, April 28, 2013

Download / Upload any file and Display Message using C# in ASP.NET

* To display information using message box in ASP.NET page from server side code.

static public void DisplayAJAXMessage(Control page, string msg)
    {
            string myScript = String.Format("alert('{0}');", msg);
            ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);      
    }


e.g. : DisplayAJAXMessage(this, "Hello World");
OUTPUT: 
Fig 1: Output of DisplayAjaxMessage


* Download a file from server using link button:

protected void lnkDownloadFile_Click(object sender, EventArgs e)
    {
        try
        {
            string FileName = string.Empty;
            FileName = "demo.xls"; // Any File Name with extension
            string link = Server.MapPath("<~/Folder Name/>" + FileName); //Optional Folder Name
            FileInfo myfile = new FileInfo(link);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
            Response.AddHeader("Content-Length", myfile.Length.ToString());
            Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
            Response.TransmitFile(myfile.FullName);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            DisplayAJAXMessage(this, "File Not Found");
        }
    }


private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".xls":
                // case ".csv":
                return "application/vnd.ms-excel";
            default:
                return "application/octet-stream";
        }
    }


* Upload any file to server using C# in ASP.NET 
(Note: This example shows to upload excel file (.xls) , Just change the extension of file as per requirement to upload any type file.)

  protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (UploadFile.HasFile) //FileUpload tool from ToolBox
            {
                string Extension = Path.GetExtension(UploadFile.PostedFile.FileName);
                if (Convert.ToString(Extension).ToLower() != ".xls")
                {
                    lblError.Text = "Please select a file with extension .xls before validation";
                    return;
                }
            }
            else
            {
                lblError.Text = "Please select a file with extension .xls before validation";
                return;
            }
            string uploadFileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            int index = uploadFileName.LastIndexOf('.');
            string SheetName = uploadFileName.Substring(0, index);
            string FileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            string FilePath = Server.MapPath("~//" + FileName); //Optional FolderName
            UploadFile.SaveAs(FilePath);
         }
        catch (Exception ex)
        {
           DisplayAJAXMessage(this,"Error::"+ex);

        }
    }


Happy Coding 



View Amit Lal's profile on LinkedIn

Software Developer, Academic Writing Writer

Wednesday, November 28, 2012

Display a file in NewPage and export a file to Excel.

Display a file on Link Button Click.


protected void linkbtnFile_Click(object sender, EventArgs e)
    {
        string link =  Server.MapPath(".") + "\\\\" +;
        Response.ContentType = "application/"+linkbtnFile.Text.Substring(linkbtnFile.Text.IndexOf('.')+1);
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + link);
        Response.TransmitFile(link);
        Response.End();
    }


Export a File from Radgrid to Excel file.

protected void btnExport_Click(object sender, EventArgs e)
    {
        RadGrid1.MasterTableView.ExportToExcel();
        RadGrid1.ExportSettings.ExportOnlyData = true;
        RadGrid1.ExportSettings.IgnorePaging = true;
        RadGrid1.ExportSettings.OpenInNewWindow = true;
    }

Friday, September 28, 2012

Export data from GridView/DataTable to Excel File using C#.NET for webpage and VB.NET window based application

How to Export GridViewData to Excel File using C#.NET ?

Step 1 : Create a function for Change Controls To Value :

private void ChangeControlsToValue(Control gridView)
    {
        Literal literal = new Literal();
       
        for (int i = 0; i < gridView.Controls.Count; i++)
        {
            if (gridView.Controls[i].GetType() == typeof(LinkButton))
            {

                literal.Text = (gridView.Controls[i] as LinkButton).Text;
                gridView.Controls.Remove(gridView.Controls[i]);
                gridView.Controls.AddAt(i,literal);
            }
            else if (gridView.Controls[i].GetType() == typeof(DropDownList))
            {
                literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;

                gridView.Controls.Remove(gridView.Controls[i]);

                gridView.Controls.AddAt(i,literal);

            }
            else if (gridView.Controls[i].GetType() == typeof(CheckBox))
            {
                literal.Text = (gridView.Controls[i] as CheckBox).Checked ? "True" : "False";
                gridView.Controls.Remove(gridView.Controls[i]);
                gridView.Controls.AddAt(i,literal);
            }
            if (gridView.Controls[i].HasControls())
            {

                ChangeControlsToValue(gridView.Controls[i]);

            }

        }

    }


Step 2 : On Button Click to export data, Add the following Code :

protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedIndex == 0)
        {
            GridView1.AllowPaging = false;
            GridView1.GridLines = GridLines.None;
            GridView1.DataBind();
        }
        else
        {
            GridView1.PagerSettings.Visible = false;
            GridView1.GridLines = GridLines.None;
            GridView1.DataBind();
        }

        ChangeControlsToValue(GridView1);
        Response.ClearContent();

        Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");

        Response.ContentType = "application/excel";

        StringWriter sWriter = new StringWriter();

        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);

        HtmlForm hForm = new HtmlForm();

        GridView1.Parent.Controls.Add(hForm);

        hForm.Attributes["runat"] = "server";

        hForm.Controls.Add(GridView1);

        hForm.RenderControl(hTextWriter);
       
        // Write below code to add cell border to empty cells in Excel file
        // If we don't add this line then empty cells will be shown as blank white space

        StringBuilder sBuilder = new StringBuilder();
        sBuilder.Append(" <!--[if gte mso 9]>ExportToExcel<![endif]
");
        sBuilder.Append(sWriter + "-->");
        Response.Write(sBuilder.ToString());

        Response.End();
    }

 Export data from data table to excel file in window based application using VB.NET

Private Sub exporttoexcel(ByVal dtable As DataTable)

        Dim strTempFile As String = My.Computer.FileSystem.GetTempFileName()

        Dim strLine As New Text.StringBuilder("")

        For c As Integer = 0 To dtable.Columns.Count - 1
            strLine.Append(dtable.Columns(c).ColumnName.ToString & ",")
        Next

        My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)

        For r As Integer = 0 To dtable.Rows.Count - 1
            strLine = New Text.StringBuilder("")
            For c As Integer = 0 To dtable.Columns.Count - 1
                strLine.Append(dtable.Rows(r).Item(c).ToString & ",")
            Next

            My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)
        Next

        Process.Start("excel", strTempFile)
    End Sub
-----------------------------------------------------------------------------------------------------------------------
Call this function on button click event to export the rows of the data table to excel file

View Amit Lal's profile on LinkedIn
Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Sunday, April 28, 2013

Download / Upload any file and Display Message using C# in ASP.NET

* To display information using message box in ASP.NET page from server side code.

static public void DisplayAJAXMessage(Control page, string msg)
    {
            string myScript = String.Format("alert('{0}');", msg);
            ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);      
    }


e.g. : DisplayAJAXMessage(this, "Hello World");
OUTPUT: 
Fig 1: Output of DisplayAjaxMessage


* Download a file from server using link button:

protected void lnkDownloadFile_Click(object sender, EventArgs e)
    {
        try
        {
            string FileName = string.Empty;
            FileName = "demo.xls"; // Any File Name with extension
            string link = Server.MapPath("<~/Folder Name/>" + FileName); //Optional Folder Name
            FileInfo myfile = new FileInfo(link);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);
            Response.AddHeader("Content-Length", myfile.Length.ToString());
            Response.ContentType = ReturnExtension(myfile.Extension.ToLower());
            Response.TransmitFile(myfile.FullName);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex)
        {
            DisplayAJAXMessage(this, "File Not Found");
        }
    }


private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".xls":
                // case ".csv":
                return "application/vnd.ms-excel";
            default:
                return "application/octet-stream";
        }
    }


* Upload any file to server using C# in ASP.NET 
(Note: This example shows to upload excel file (.xls) , Just change the extension of file as per requirement to upload any type file.)

  protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (UploadFile.HasFile) //FileUpload tool from ToolBox
            {
                string Extension = Path.GetExtension(UploadFile.PostedFile.FileName);
                if (Convert.ToString(Extension).ToLower() != ".xls")
                {
                    lblError.Text = "Please select a file with extension .xls before validation";
                    return;
                }
            }
            else
            {
                lblError.Text = "Please select a file with extension .xls before validation";
                return;
            }
            string uploadFileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            int index = uploadFileName.LastIndexOf('.');
            string SheetName = uploadFileName.Substring(0, index);
            string FileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            string FilePath = Server.MapPath("~//" + FileName); //Optional FolderName
            UploadFile.SaveAs(FilePath);
         }
        catch (Exception ex)
        {
           DisplayAJAXMessage(this,"Error::"+ex);

        }
    }


Happy Coding 



View Amit Lal's profile on LinkedIn

Software Developer, Academic Writing Writer

Wednesday, November 28, 2012

Display a file in NewPage and export a file to Excel.

Display a file on Link Button Click.


protected void linkbtnFile_Click(object sender, EventArgs e)
    {
        string link =  Server.MapPath(".") + "\\\\" +;
        Response.ContentType = "application/"+linkbtnFile.Text.Substring(linkbtnFile.Text.IndexOf('.')+1);
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + link);
        Response.TransmitFile(link);
        Response.End();
    }


Export a File from Radgrid to Excel file.

protected void btnExport_Click(object sender, EventArgs e)
    {
        RadGrid1.MasterTableView.ExportToExcel();
        RadGrid1.ExportSettings.ExportOnlyData = true;
        RadGrid1.ExportSettings.IgnorePaging = true;
        RadGrid1.ExportSettings.OpenInNewWindow = true;
    }

Friday, September 28, 2012

Export data from GridView/DataTable to Excel File using C#.NET for webpage and VB.NET window based application

How to Export GridViewData to Excel File using C#.NET ?

Step 1 : Create a function for Change Controls To Value :

private void ChangeControlsToValue(Control gridView)
    {
        Literal literal = new Literal();
       
        for (int i = 0; i < gridView.Controls.Count; i++)
        {
            if (gridView.Controls[i].GetType() == typeof(LinkButton))
            {

                literal.Text = (gridView.Controls[i] as LinkButton).Text;
                gridView.Controls.Remove(gridView.Controls[i]);
                gridView.Controls.AddAt(i,literal);
            }
            else if (gridView.Controls[i].GetType() == typeof(DropDownList))
            {
                literal.Text = (gridView.Controls[i] as DropDownList).SelectedItem.Text;

                gridView.Controls.Remove(gridView.Controls[i]);

                gridView.Controls.AddAt(i,literal);

            }
            else if (gridView.Controls[i].GetType() == typeof(CheckBox))
            {
                literal.Text = (gridView.Controls[i] as CheckBox).Checked ? "True" : "False";
                gridView.Controls.Remove(gridView.Controls[i]);
                gridView.Controls.AddAt(i,literal);
            }
            if (gridView.Controls[i].HasControls())
            {

                ChangeControlsToValue(gridView.Controls[i]);

            }

        }

    }


Step 2 : On Button Click to export data, Add the following Code :

protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedIndex == 0)
        {
            GridView1.AllowPaging = false;
            GridView1.GridLines = GridLines.None;
            GridView1.DataBind();
        }
        else
        {
            GridView1.PagerSettings.Visible = false;
            GridView1.GridLines = GridLines.None;
            GridView1.DataBind();
        }

        ChangeControlsToValue(GridView1);
        Response.ClearContent();

        Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls");

        Response.ContentType = "application/excel";

        StringWriter sWriter = new StringWriter();

        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);

        HtmlForm hForm = new HtmlForm();

        GridView1.Parent.Controls.Add(hForm);

        hForm.Attributes["runat"] = "server";

        hForm.Controls.Add(GridView1);

        hForm.RenderControl(hTextWriter);
       
        // Write below code to add cell border to empty cells in Excel file
        // If we don't add this line then empty cells will be shown as blank white space

        StringBuilder sBuilder = new StringBuilder();
        sBuilder.Append(" <!--[if gte mso 9]>ExportToExcel<![endif]
");
        sBuilder.Append(sWriter + "-->");
        Response.Write(sBuilder.ToString());

        Response.End();
    }

 Export data from data table to excel file in window based application using VB.NET

Private Sub exporttoexcel(ByVal dtable As DataTable)

        Dim strTempFile As String = My.Computer.FileSystem.GetTempFileName()

        Dim strLine As New Text.StringBuilder("")

        For c As Integer = 0 To dtable.Columns.Count - 1
            strLine.Append(dtable.Columns(c).ColumnName.ToString & ",")
        Next

        My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)

        For r As Integer = 0 To dtable.Rows.Count - 1
            strLine = New Text.StringBuilder("")
            For c As Integer = 0 To dtable.Columns.Count - 1
                strLine.Append(dtable.Rows(r).Item(c).ToString & ",")
            Next

            My.Computer.FileSystem.WriteAllText(strTempFile, strLine.ToString.TrimEnd(",") & vbCrLf, True)
        Next

        Process.Start("excel", strTempFile)
    End Sub
-----------------------------------------------------------------------------------------------------------------------
Call this function on button click event to export the rows of the data table to excel file

View Amit Lal's profile on LinkedIn