Hi Mehram,
Check this example. Now please take its reference and correct your code.
HTML
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="ImageName" HeaderText="Name" />
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="imgPath" runat="server" Width="100" hight="100"
ImageUrl='<%# Eval("Path", GetUrl("{0}")) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExportExcel" runat="server" Text="Export" OnClick="OnExport" />
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.IO
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGridView();
}
}
protected void OnExport(object sender, EventArgs e)
{
if (!Directory.Exists(Server.MapPath("~/Photos")))
{
Directory.CreateDirectory(Server.MapPath("~/Photos"));
}
DeleteTempImages(Server.MapPath("~/Photos"));
gvFiles.AllowPaging = false;
this.BindGridView();
foreach (GridViewRow row in gvFiles.Rows)
{
string imageName = row.Cells[1].Text;
GenerateThumbNail("Images/" + imageName, "Photos/" + imageName, 100);
(row.FindControl("imgPath") as System.Web.UI.WebControls.Image).ImageUrl = GetUrl("Photos/" + imageName);
row.Attributes.Add("class", "textmode");
row.Height = 100;
row.Cells[2].Width = 100;
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridView.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvFiles.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
private void BindGridView()
{
DataTable dt = new DataTable();
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand("SELECT TOP 4 * FROM tblFilePath"))
{
using (SqlConnection con = new SqlConnection(strConnString))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
sda.Fill(dt);
gvFiles.DataSource = dt;
gvFiles.DataBind();
}
}
}
}
public void GenerateThumbNail(string sourceFile, string destinationFile, int width)
{
if (File.Exists(Server.MapPath(sourceFile)))
{
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(sourceFile));
int srcWidth = image.Width;
int srcHeight = image.Height;
int thumbWidth = width;
int thumbHeight;
Bitmap bmp;
if (srcHeight > srcWidth)
{
thumbHeight = (srcHeight / srcWidth) * thumbWidth;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
else
{
thumbHeight = thumbWidth;
thumbWidth = (srcWidth / srcHeight) * thumbHeight;
bmp = new Bitmap(thumbWidth, thumbHeight);
}
Graphics gr = Graphics.FromImage(bmp);
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.CompositingQuality = CompositingQuality.HighQuality;
gr.InterpolationMode = InterpolationMode.High;
Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
bmp.Save(Server.MapPath(destinationFile));
bmp.Dispose();
image.Dispose();
}
}
private void DeleteTempImages(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
protected string GetUrl(string imagePath)
{
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 + imagePath;
}
return imagePath;
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGridView()
End If
End Sub
Protected Sub OnExport(ByVal sender As Object, ByVal e As EventArgs)
If Not Directory.Exists(Server.MapPath("~/Photos")) Then
Directory.CreateDirectory(Server.MapPath("~/Photos"))
End If
DeleteTempImages(Server.MapPath("~/Photos"))
gvFiles.AllowPaging = False
Me.BindGridView()
For Each row As GridViewRow In gvFiles.Rows
Dim imageName As String = row.Cells(1).Text
GenerateThumbNail("Images/" & imageName, "Photos/" & imageName, 100)
TryCast(row.FindControl("imgPath"), WebControls.Image).ImageUrl = GetUrl("Photos/" & imageName)
row.Attributes.Add("class", "textmode")
row.Height = 100
row.Cells(2).Width = 100
Next
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridView.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As StringWriter = New StringWriter()
Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
gvFiles.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
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Private Sub BindGridView()
Dim dt As DataTable = New DataTable()
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using cmd As SqlCommand = New SqlCommand("SELECT TOP 4 * FROM tblFilePath")
Using con As SqlConnection = New SqlConnection(strConnString)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Using sda As SqlDataAdapter = New SqlDataAdapter()
sda.SelectCommand = cmd
sda.Fill(dt)
gvFiles.DataSource = dt
gvFiles.DataBind()
End Using
End Using
End Using
End Sub
Public Sub GenerateThumbNail(ByVal sourceFile As String, ByVal destinationFile As String, ByVal width As Integer)
If File.Exists(Server.MapPath(sourceFile)) Then
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath(sourceFile))
Dim srcWidth As Integer = image.Width
Dim srcHeight As Integer = image.Height
Dim thumbWidth As Integer = width
Dim thumbHeight As Integer
Dim bmp As Bitmap
If srcHeight > srcWidth Then
thumbHeight = (srcHeight / srcWidth) * thumbWidth
bmp = New Bitmap(thumbWidth, thumbHeight)
Else
thumbHeight = thumbWidth
thumbWidth = (srcWidth / srcHeight) * thumbHeight
bmp = New Bitmap(thumbWidth, thumbHeight)
End If
Dim gr As Graphics = Graphics.FromImage(bmp)
gr.SmoothingMode = SmoothingMode.HighQuality
gr.CompositingQuality = CompositingQuality.HighQuality
gr.InterpolationMode = InterpolationMode.High
Dim rectDestination As Rectangle = New Rectangle(0, 0, thumbWidth, thumbHeight)
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel)
bmp.Save(Server.MapPath(destinationFile))
bmp.Dispose()
image.Dispose()
End If
End Sub
Private Sub DeleteTempImages(path As String)
Dim di As DirectoryInfo = New DirectoryInfo(path)
For Each file As FileInfo In di.GetFiles()
file.Delete()
Next
For Each dir As DirectoryInfo In di.GetDirectories()
dir.Delete(True)
Next
End Sub
Protected Function GetUrl(ByVal imagePath 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 & imagePath
End If
Return imagePath
End Function
Screenshots
GridView
Exported Excel