概要:
中午睡了一會,醒來的時候看到老師叫我去辦公室,需求是這樣的,把excel表中的每個同學,判斷圖片目錄中是否有對應的照片(圖片的名字用的學號或身份證號碼)
沒有對應圖片的學生記錄,存入自己的數據表中或直接輸出,最后下載成Excel
於是回去后他把Excel和照片發給我
正文開始:
雖然沒接觸過Excel的數據導入和將GridView數據導出Excel,在網上查找了很多資料,最后匯總成功實現。
這是第一次寫自己的博客並與大家分享。



我也是查了百度學來的,詳細地址:
http://jingyan.baidu.com/article/47a29f24003521c0142399dc.html
2.將圖片目錄所有圖片對應的名稱導入另外一張表(image表),圖片有些多並且如何能達到高效遍歷目錄文件,於是又去查百度了!地址如下:
http://blog.csdn.net/love_rrr/article/details/7779403
http://www.cnblogs.com/xdesigner/archive/2006/12/08/586177.html
代碼如下:
#region 聲明WIN32API函數以及結構 ************************************** [Serializable, System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Auto ), System.Runtime.InteropServices.BestFitMapping(false)] private struct WIN32_FIND_DATA { public int dwFileAttributes; public int ftCreationTime_dwLowDateTime; public int ftCreationTime_dwHighDateTime; public int ftLastAccessTime_dwLowDateTime; public int ftLastAccessTime_dwHighDateTime; public int ftLastWriteTime_dwLowDateTime; public int ftLastWriteTime_dwHighDateTime; public int nFileSizeHigh; public int nFileSizeLow; public int dwReserved0; public int dwReserved1; [System.Runtime.InteropServices.MarshalAs (System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [System.Runtime.InteropServices.MarshalAs (System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [System.Runtime.InteropServices.DllImport ("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData); [System.Runtime.InteropServices.DllImport ("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] private static extern bool FindNextFile(IntPtr hndFindFile, ref WIN32_FIND_DATA lpFindFileData); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] private static extern bool FindClose(IntPtr hndFindFile); #endregion //具體方法函數 Stack<string> m_scopes = new Stack<string>(); private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); WIN32_FIND_DATA FindFileData; private System.IntPtr hFind = INVALID_HANDLE_VALUE; void FindFileInDir(string rootDir) { string path = rootDir; start: new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Path.Combine(path, ".")).Demand(); if (path[path.Length - 1] != '\\') { path = path + "\\"; } Response.Write("文件夾為:"+path+"<br>"); hFind = FindFirstFile(Path.Combine(path,"*"), ref FindFileData); if(hFind!=INVALID_HANDLE_VALUE) { do { if (FindFileData.cFileName.Equals(@".") || FindFileData.cFileName.Equals(@"..")) continue; if ((FindFileData.dwFileAttributes & 0x10) != 0) { m_scopes.Push(Path.Combine(path, FindFileData.cFileName)); } else { Response.Write(FindFileData.cFileName+"<br>"); } } while (FindNextFile(hFind, ref FindFileData)); } FindClose(hFind); if (m_scopes.Count > 0) { path = m_scopes.Pop(); goto start; } } //調用方法如下: FindFileInDir(@"D:\images\images"); //絕對路徑
3.(再次看了下需求)按照需求把Page2表中的每個同學,判斷image表中是否有對應的照片
沒有對應圖片的學生記錄,輸出到GridView,最后下載成Excel
頁面布局
代碼如下:
<div style="width:100%"> 查詢條件:<asp:DropDownList ID="DropDownList1" runat="server"> <asp:ListItem Value="0" Text="=查詢所有="></asp:ListItem> <asp:ListItem Value="1" Text="=身份證ID查詢="></asp:ListItem> <asp:ListItem Value="2" Text="=姓名查詢="></asp:ListItem> </asp:DropDownList> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button2" runat="server" Text="查詢" OnClick="Button2_Click" style="height: 21px" /> <asp:Button ID="Button1" runat="server" Text="下載EXCEL" onclick="Button1_Click" /> <br /> <br /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%" PageSize="15"> <Columns> <asp:TemplateField HeaderText="序號"> <ItemTemplate><%#Eval("RowNum") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="用戶ID"> <ItemTemplate><%#Eval("UserID") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="用戶姓名"> <ItemTemplate><%#Eval("Name") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="身份證號"> <ItemTemplate><%#Eval("PassCardID") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="性別"> <ItemTemplate><%#Eval("Sex") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="學院"> <ItemTemplate><%#Eval("College") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="班級名稱"> <ItemTemplate><%#Eval("ClassName") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="年級"> <ItemTemplate><%#Eval("ClassID") %></ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <br /> <webdiyer:AspNetPager ID="AspNetPager1" runat="server" FirstPageText="首頁" LastPageText="尾頁" NextPageText="下一頁" PrevPageText="上一頁" PageSize="20" onpagechanged="AspNetPager1_PageChanged"> </webdiyer:AspNetPager> <div> </div> </div>
后台代碼如下:
public void BindPagerPage(GridView gv, AspNetPager pager)
{
string sql = "with page as (select *,Row_number() OVER (ORDER BY UserID desc)as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page where RowNum>{0} and RowNum<{1}";
sql = string.Format(sql, (pager.CurrentPageIndex - 1) * pager.PageSize, (pager.CurrentPageIndex - 1) * pager.PageSize + pager.PageSize);
pager.RecordCount = int.Parse(new DataBase().ExecuteValue("with page as(select Count(*) as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select RowNum from page"));
gv.DataSource = new DataBase().GetDataTable(sql);
gv.DataBind();
}
因為用到了AspNetPager開源分頁控件,想在GridView上展示良好的分頁效果完成,開始編寫的數據庫語句數據出現重復,最后修改的時候數據庫語句反復出現錯誤跟着提示,才使數據無重復效果,如果有比較好的語句可以教下我,謝謝!(這里因為數據重復花了不少時間)

數據確實有點多,剩下的圖片由於太多了,在QQ上傳文件接收又慢,最后拿了老師發了我30多張圖片我做下測試。
數據得到了良好的展示!
4.最后一步是最關鍵:將GridView數據導出Excel,在這里我又用到了一個開源控件MyXls.SL2
protected void Button1_Click(object sender, EventArgs e)
{
string strsql = " with page as (select *,Row_number() OVER (ORDER BY UserID asc)as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page";
Dal.DataBase db = new Dal.DataBase();
ExcelDown exceldown = new ExcelDown();
exceldown.downExcel(Response, db.GetDataTable(strsql), "page" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond, Server.MapPath("~/Excel"));
}
總結:這次任務完成,並且也學到了將GridView數據導出Excel,自己是從大一下學期開始接觸C#學了一段時間后開始學習asp.net,當時什么都不懂,老師就給我一些小案例去做,開始百度找的學習視頻都是很模糊,看的時候很少敲代碼導致后來太久不用了就忘記了,學習效率非常低,,接下來的日子里每天都是看別人寫的博客和看一些項目案例視頻學習敲代碼並且自己把做好的小模塊、知識點整理起來等要用的時候就復制粘貼,也得到了老師和學長的幫助,很感謝他們,寫博客就是想認識多一些人交流學習,保持學習的狀態!
完整代碼
ExcelDown.cs
namespace Dal
{
public class ExcelDown
{
public void downExcel(HttpResponse response, DataTable dt, string fileName, string path)
{
XlsDocument xls = new XlsDocument();//新建一個
xls.FileName = fileName + ".xls";
Worksheet sheet = xls.Workbook.Worksheets.Add("Sheet1");
//填充表頭
try
{
foreach (DataColumn col in dt.Columns)
{
sheet.Cells.Add(1, col.Ordinal + 1, col.ColumnName);
}
//填充內容
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sheet.Cells.Add(i + 2, j + 1, dt.Rows[i][j].ToString());
}
}
#region
using (MemoryStream ms = new MemoryStream())
{
xls.Save(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
xls = null;
// HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.Charset = "UTF-8";
response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + fileName + ".xls"));
//System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
byte[] data = ms.ToArray();
System.Web.HttpContext.Current.Response.BinaryWrite(data);
}
#endregion
}
finally
{
sheet = null;
xls = null;
}
}
}
}
PageDal.cs
public void BindPagerPage(GridView gv, AspNetPager pager)
{
string sql = "with page as (select *,Row_number() OVER (ORDER BY UserID desc)as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page where RowNum>{0} and RowNum<{1}";
sql = string.Format(sql, (pager.CurrentPageIndex - 1) * pager.PageSize, (pager.CurrentPageIndex - 1) * pager.PageSize + pager.PageSize);
pager.RecordCount = int.Parse(new DataBase().ExecuteValue("with page as(select Count(*) as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select RowNum from page"));
gv.DataSource = new DataBase().GetDataTable(sql);
gv.DataBind();
}
page.aspx
public partial class Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) { bind();
// FindFileInDir(@"D:\images\images"); //絕對路徑 只用一次用完記得注釋
}
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
bind();
}
public void bind()
{
new PageDal().BindPagerPage(GridView1, AspNetPager1);
}
protected void Button1_Click(object sender, EventArgs e)
{
string strsql = " with page as (select *,Row_number() OVER (ORDER BY UserID asc)as RowNum from Page2 where not exists (select imagename from dbo.[image] where Page2.UserID=dbo.[image].imagename or Page2.PassCardID = dbo.[image].imagename) )select * from page";
Dal.DataBase db = new Dal.DataBase();
ExcelDown exceldown = new ExcelDown();
exceldown.downExcel(Response, db.GetDataTable(strsql), "Page" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "-" + DateTime.Now.Millisecond, Server.MapPath("~/Excel"));
}
protected void Button2_Click(object sender, EventArgs e)
{
// bind();//點擊查詢
}
#region 聲明WIN32API函數以及結構 **************************************
[Serializable,
System.Runtime.InteropServices.StructLayout
(System.Runtime.InteropServices.LayoutKind.Sequential,
CharSet = System.Runtime.InteropServices.CharSet.Auto
),
System.Runtime.InteropServices.BestFitMapping(false)]
private struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public int ftCreationTime_dwLowDateTime;
public int ftCreationTime_dwHighDateTime;
public int ftLastAccessTime_dwLowDateTime;
public int ftLastAccessTime_dwHighDateTime;
public int ftLastWriteTime_dwLowDateTime;
public int ftLastWriteTime_dwHighDateTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
[System.Runtime.InteropServices.MarshalAs
(System.Runtime.InteropServices.UnmanagedType.ByValTStr,
SizeConst = 260)]
public string cFileName;
[System.Runtime.InteropServices.MarshalAs
(System.Runtime.InteropServices.UnmanagedType.ByValTStr,
SizeConst = 14)]
public string cAlternateFileName;
}
[System.Runtime.InteropServices.DllImport
("kernel32.dll",
CharSet = System.Runtime.InteropServices.CharSet.Auto,
SetLastError = true)]
private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
[System.Runtime.InteropServices.DllImport
("kernel32.dll",
CharSet = System.Runtime.InteropServices.CharSet.Auto,
SetLastError = true)]
private static extern bool FindNextFile(IntPtr hndFindFile, ref WIN32_FIND_DATA lpFindFileData);
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FindClose(IntPtr hndFindFile);
#endregion
//具體方法函數
Stack<string> m_scopes = new Stack<string>();
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
WIN32_FIND_DATA FindFileData;
private System.IntPtr hFind = INVALID_HANDLE_VALUE;
void FindFileInDir(string rootDir)
{
string path = rootDir;
start:
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Path.Combine(path, ".")).Demand();
if (path[path.Length - 1] != '\\')
{
path = path + "\\";
}
Response.Write("文件夾為:"+path+"<br>");
hFind = FindFirstFile(Path.Combine(path,"*"), ref FindFileData);
if(hFind!=INVALID_HANDLE_VALUE)
{
do
{
if (FindFileData.cFileName.Equals(@".") || FindFileData.cFileName.Equals(@".."))
continue;
if ((FindFileData.dwFileAttributes & 0x10) != 0)
{
m_scopes.Push(Path.Combine(path, FindFileData.cFileName));
}
else
{
Response.Write(FindFileData.cFileName+"<br>");
string[] str =FindFileData.cFileName.Split('.');
DataBase db = new DataBase();
string comstr = "insert into Image(imageName) values(@ImageName)";
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("@ImageName", SqlDbType.VarChar, 256);
param[0].Value = str[0];
db.ExecuteSql(comstr, param);
}
}
while (FindNextFile(hFind, ref FindFileData));
}
FindClose(hFind);
if (m_scopes.Count > 0)
{
path = m_scopes.Pop();
goto start;
}
}
}
