Hi
Please refer below smaple for excel, And refer below link for PDF.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Font-Names="Arial">
<Columns>
<asp:BoundField DataField="ID" ItemStyle-Height="150" HeaderText="ID" />
<asp:BoundField DataField="Name" ItemStyle-Height="150" HeaderText="Image Name" />
<asp:TemplateField ItemStyle-Height="150" ItemStyle-Width="170" HeaderText="Image Preview">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ID", GetUrl("ImageCSharp.aspx?ImageID={0}"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button Text="ExportToExcel" runat="server" OnClick="printExcel_Click" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
VB.Net
Imports System.IO
Imports System.Data.SqlClient
Imports System.Data
Code
C#
CS.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("select ID, Name from tblFiles order by ID", conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected string GetUrl(string page)
{
string[] splits = Request.Url.AbsoluteUri.Split('/');
if (splits.Length >= 2)
{
string url = splits[0] + "//";
for (int i = 2; i < splits.Length - 1; i++)
{
url += splits[i];
url += "/";
}
return url + page;
}
return page;
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void printExcel_Click(object sender, EventArgs e)
{
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);
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = System.Drawing.Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
cell.Width = 200;
cell.Height = 150;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
cell.Width = 150;
cell.Height = 100;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
ImageCSharp.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ImageID"] != null)
{
string strQuery = "select Name, ContentType, Data from tblFiles where id=@id";
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
}
catch
{
dt = null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
VB.Net
VB.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter("select ID, Name from tblFiles order by ID", conn)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End If
End Sub
Protected Function GetUrl(ByVal page As String) As String
Dim splits As String() = Request.Url.AbsoluteUri.Split("/"c)
If splits.Length >= 2 Then
Dim url As String = splits(0) & "//"
For i As Integer = 2 To splits.Length - 1 - 1
url += splits(i)
url += "/"
Next
Return url & page
End If
Return page
End Function
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Protected Sub printExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As StringWriter = New StringWriter()
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
For Each cell As TableCell In GridView1.HeaderRow.Cells
cell.BackColor = GridView1.HeaderStyle.BackColor
Next
For Each row As GridViewRow In GridView1.Rows
row.BackColor = System.Drawing.Color.White
For Each cell As TableCell In row.Cells
If row.RowIndex Mod 2 = 0 Then
cell.BackColor = GridView1.AlternatingRowStyle.BackColor
cell.Width = 200
cell.Height = 150
Else
cell.BackColor = GridView1.RowStyle.BackColor
cell.Width = 150
cell.Height = 100
End If
cell.CssClass = "textmode"
Next
Next
GridView1.RenderControl(hw)
Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
ImageVB.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("ImageID") IsNot Nothing Then
Dim strConnString As String = System.Configuration. _
ConfigurationManager.ConnectionStrings("constr") _
.ConnectionString
Dim strQuery As String = "select Name, ContentType," _
& " Data from tblFiles where id=@id"
Dim cmd As SqlCommand = New SqlCommand(strQuery)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = _
Convert.ToInt32(Request.QueryString("ImageID"))
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Dim dt As New DataTable
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Catch ex As Exception
dt = Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
If dt IsNot Nothing Then
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", _
"attachment;filename=" _
& dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End If
End If
End Sub
Screenshot
