前臺datagrid數據綁定html
#region 導出到excel中
/// <summary>
/// 2014-6-6
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
app
protected void lnkbtnExcel_Click(object sender, EventArgs e)//導出Excel按鈕點擊事件
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("tblExXuQiu");
ds.Tables.Add(dt);
//dgResEleList dataGrid控件ide
//導出的excel的標題網站
dt.Columns.Add(new DataColumn("序列號", System.Type.GetType("System.String")));//序列號
dt.Columns.Add(new DataColumn("區縣局", System.Type.GetType("System.String")));//區縣局
dt.Columns.Add(new DataColumn("2013任務", System.Type.GetType(" System.String")));//2013任務
dt.Columns.Add(new DataColumn("已改造", System.Type.GetType(" System.String")));//已改造
dt.Columns.Add(new DataColumn("已更新", System.Type.GetType(" System.String")));//已更新
dt.Columns.Add(new DataColumn("已完成小計", System.Type.GetType(" System.String")));//已完成小計
dt.Columns.Add(new DataColumn("未完成小計", System.Type.GetType(" System.String")));//未完成小計
if (dgResEleList.Items.Count == 0)
{
JSUAlter.Alert(this.Page, "沒有數據 沒法導出");
return;
}
else
{
for (int i = 0; i < dgResEleList2013.Items.Count; i++)
{
DataRow dr = dt.NewRow();
if (dgResEleList2013.Items[i].ItemType == ListItemType.Item || dgResEleList2013.Items[i].ItemType == ListItemType.AlternatingItem || dgResEleList2013.Items[i].ItemType == ListItemType.SelectedItem)
{ui
//前臺使用綁定數據this
//後臺取值3d
dr["序列號"] = (dgResEleList2013.Items[i].Cells[0].FindControl("SeqLB1") as Label).Text.Trim();excel
//前臺使用<asp:BoundColumn DataField="int2013" HeaderText="2013任務"></asp:BoundColumn>綁定數據
dr["區縣局"] = dgResEleList2013.Items[i].Cells[1].Text.Trim();code
dr["2013任務"] = dgResEleList2013.Items[i].Cells[2].Text.Trim();
dr["已改造"] = (dgResEleList2013.Items[i].Cells[3].FindControl("intGZ1") as Label).Text.Trim();
dr["已更新"] = (dgResEleList2013.Items[i].Cells[4].FindControl("intGX1") as Label).Text.Trim();
dr["已完成小計"] = (dgResEleList2013.Items[i].Cells[5].FindControl("intFTotal1") as Label).Text.Trim();
dr["未完成小計"] = (dgResEleList2013.Items[i].Cells[6].FindControl("intUTotal1") as Label).Text.Trim();
dt.Rows.Add(dr);
}
}htm
//調用ExcelHelper類 傳入參數 數據源 excel名稱
ExcelHelper.DataTable3Excel(ds.Tables[0], "Excel" + DateTime.Now.ToString("yyyy-MM-dd"));
}
}
#endregion
ExcelHelper類
/// <summary>
/// 類說明:Assistant
/// 編 碼 人:
/// 聯繫方式:
/// 更新網站:
/// </summary>
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Data.OleDb;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wsl.WorkFrame;
/// <summary>
/// Excel操做類
/// </summary>
/// Microsoft Excel 11.0 Object Library
public class ExcelHelper : SqlDaoObject
{
#region 數據導出至Excel文件
/// </summary>
/// 導出Excel文件,自動返回可下載的文件流
/// </summary>
public static void DataTable1Excel(System.Data.DataTable dtData)
{
GridView gvExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Charset = "utf-8";
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
gvExport = new GridView();
gvExport.DataSource = dtData.DefaultView;
gvExport.AllowPaging = false;
gvExport.DataBind();
gvExport.RenderControl(htmlWriter);
curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString());
curContext.Response.End();
}
}
#region 導出Excel文件,轉換爲可讀模式
/// <summary>
/// 導出Excel文件,轉換爲可讀模式
/// </summary>
public static void DataTable2Excel(System.Data.DataTable dtData)
{
DataGrid dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "";
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new DataGrid();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
#endregion
#region 導出Excel文件,並自定義文件名
/// <summary>
/// 導出Excel文件,並自定義文件名
/// </summary>
public static void DataTable3Excel(System.Data.DataTable dtData, String FileName)
{
GridView dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
curContext.Response.Clear();
HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
//Response.AppendHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
curContext.Response.AddHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
curContext.Response.ContentType = "application/ms-excel";
curContext.Response.Charset = "GB2312";
// curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=gb2312\"/>" +strWriter.ToString());
curContext.Response.End();
//curContext.ApplicationInstance.CompleteRequest();
}
}
#endregion
#region 導出Excel文件,並自定義文件名 record
/// <summary>
/// 導出Excel文件,並自定義文件名 record
/// </summary>
public static void DataTableRecExcel(System.Data.DataTable dtData, String FileName)
{
GridView dgExport = null;
HttpContext curContext = HttpContext.Current;
StringWriter strWriter = null;
HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
//Response.AppendHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
curContext.Response.AddHeader("content-disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
curContext.Response.ContentType = "application/ms-excel";
curContext.Response.Charset = "GB2312";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
//curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF8");
strWriter = new StringWriter();
htmlWriter = new HtmlTextWriter(strWriter);
dgExport = new GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
#endregion
#region 將數據導出至Excel文件
/// <summary>
/// 將數據導出至Excel文件
/// </summary>
/// <param name="Table">DataTable對象</param>
/// <param name="ExcelFilePath">Excel文件路徑</param>
public static bool OutputToExcel(DataTable Table, string ExcelFilePath)
{
if (File.Exists(ExcelFilePath))
{
throw new Exception("該文件已經存在!");
}
if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
{
Table.TableName = "Sheet1";
}
//數據表的列數
int ColCount = Table.Columns.Count;
//用於記數,實例化參數時的序號
int i = 0;
//建立參數
OleDbParameter[] para = new OleDbParameter[ColCount];
//建立表結構的SQL語句
string TableStructStr = @"Create Table " + Table.TableName + "(";
//鏈接字符串
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString);
//建立表結構
OleDbCommand objCmd = new OleDbCommand();
//數據類型集合
ArrayList DataTypeList = new ArrayList();
DataTypeList.Add("System.Decimal");
DataTypeList.Add("System.Double");
DataTypeList.Add("System.Int16");
DataTypeList.Add("System.Int32");
DataTypeList.Add("System.Int64");
DataTypeList.Add("System.Single");
//遍歷數據表的全部列,用於建立表結構
foreach (DataColumn col in Table.Columns)
{
//若是列屬於數字列,則設置該列的數據類型爲double
if (DataTypeList.IndexOf(col.DataType.ToString()) >= 0)
{
para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.Double);
objCmd.Parameters.Add(para[i]);
//若是是最後一列
if (i + 1 == ColCount)
{
TableStructStr += col.ColumnName + " double)";
}
else
{
TableStructStr += col.ColumnName + " double,";
}
}
else
{
para[i] = new OleDbParameter("@" + col.ColumnName, OleDbType.VarChar);
objCmd.Parameters.Add(para[i]);
//若是是最後一列
if (i + 1 == ColCount)
{
TableStructStr += col.ColumnName + " varchar)";
}
else
{
TableStructStr += col.ColumnName + " varchar,";
}
}
i++;
}
//建立Excel文件及文件結構
try
{
objCmd.Connection = objConn;
objCmd.CommandText = TableStructStr;
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
//插入記錄的SQL語句
string InsertSql_1 = "Insert into " + Table.TableName + " (";
string InsertSql_2 = " Values (";
string InsertSql = "";
//遍歷全部列,用於插入記錄,在此建立插入記錄的SQL語句
for (int colID = 0; colID < ColCount; colID++)
{
if (colID + 1 == ColCount) //最後一列
{
InsertSql_1 += Table.Columns[colID].ColumnName + ")";
InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ")";
}
else
{
InsertSql_1 += Table.Columns[colID].ColumnName + ",";
InsertSql_2 += "@" + Table.Columns[colID].ColumnName + ",";
}
}
InsertSql = InsertSql_1 + InsertSql_2;
//遍歷數據表的全部數據行
for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
{
for (int colID = 0; colID < ColCount; colID++)
{
if (para[colID].DbType == DbType.Double && Table.Rows[rowID][colID].ToString().Trim() == "")
{
para[colID].Value = 0;
}
else
{
para[colID].Value = Table.Rows[rowID][colID].ToString().Trim();
}
}
try
{
objCmd.CommandText = InsertSql;
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string str = exp.Message;
}
}
try
{
if (objConn.State == ConnectionState.Open)
{
objConn.Close();
}
}
catch (Exception exp)
{
throw exp;
}
return true;
}
#endregion
#region 將數據導出至Excel文件
/// <summary>
/// 將數據導出至Excel文件
/// </summary>
/// <param name="Table">DataTable對象</param>
/// <param name="Columns">要導出的數據列集合</param>
/// <param name="ExcelFilePath">Excel文件路徑</param>
public static bool OutputToExcel(DataTable Table, ArrayList Columns, string ExcelFilePath)
{
if (File.Exists(ExcelFilePath))
{
throw new Exception("該文件已經存在!");
}
//若是數據列數大於表的列數,取數據表的全部列
if (Columns.Count > Table.Columns.Count)
{
for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++)
{
Columns.RemoveAt(s); //移除數據表列數後的全部列
}
}
//遍歷全部的數據列,若是有數據列的數據類型不是 DataColumn,則將它移除
DataColumn column = new DataColumn();
for (int j = 0; j < Columns.Count; j++)
{
try
{
column = (DataColumn)Columns[j];
}
catch (Exception)
{
Columns.RemoveAt(j);
}
}
if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table"))
{
Table.TableName = "Sheet1";
}
//數據表的列數
int ColCount = Columns.Count;
//建立參數
OleDbParameter[] para = new OleDbParameter[ColCount];
//建立表結構的SQL語句
string TableStructStr = @"Create Table " + Table.TableName + "(";
//鏈接字符串
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
OleDbConnection objConn = new OleDbConnection(connString);
//建立表結構
OleDbCommand objCmd = new OleDbCommand();
//數據類型集合
ArrayList DataTypeList = new ArrayList();
DataTypeList.Add("System.Decimal");
DataTypeList.Add("System.Double");
DataTypeList.Add("System.Int16");
DataTypeList.Add("System.Int32");
DataTypeList.Add("System.Int64");
DataTypeList.Add("System.Single");
DataColumn col = new DataColumn();
//遍歷數據表的全部列,用於建立表結構
for (int k = 0; k < ColCount; k++)
{
col = (DataColumn)Columns[k];
//列的數據類型是數字型
if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0)
{
para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double);
objCmd.Parameters.Add(para[k]);
//若是是最後一列
if (k + 1 == ColCount)
{
TableStructStr += col.Caption.Trim() + " Double)";
}
else
{
TableStructStr += col.Caption.Trim() + " Double,";
}
}
else
{
para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar);
objCmd.Parameters.Add(para[k]);
//若是是最後一列
if (k + 1 == ColCount)
{
TableStructStr += col.Caption.Trim() + " VarChar)";
}
else
{
TableStructStr += col.Caption.Trim() + " VarChar,";
}
}
}
//建立Excel文件及文件結構
try
{
objCmd.Connection = objConn;
objCmd.CommandText = TableStructStr;
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
throw exp;
}
//插入記錄的SQL語句
string InsertSql_1 = "Insert into " + Table.TableName + " (";
string InsertSql_2 = " Values (";
string InsertSql = "";
//遍歷全部列,用於插入記錄,在此建立插入記錄的SQL語句
for (int colID = 0; colID < ColCount; colID++)
{
if (colID + 1 == ColCount) //最後一列
{
InsertSql_1 += Columns[colID].ToString().Trim() + ")";
InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")";
}
else
{
InsertSql_1 += Columns[colID].ToString().Trim() + ",";
InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ",";
}
}
InsertSql = InsertSql_1 + InsertSql_2;
//遍歷數據表的全部數據行
DataColumn DataCol = new DataColumn();
for (int rowID = 0; rowID < Table.Rows.Count; rowID++)
{
for (int colID = 0; colID < ColCount; colID++)
{
//由於列不連續,因此在取得單元格時不能用行列編號,列需得用列的名稱
DataCol = (DataColumn)Columns[colID];
if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "")
{
para[colID].Value = 0;
}
else
{
para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim();
}
}
try
{
objCmd.CommandText = InsertSql;
objCmd.ExecuteNonQuery();
}
catch (Exception exp)
{
string str = exp.Message;
}
}
try
{
if (objConn.State == ConnectionState.Open)
{
objConn.Close();
}
}
catch (Exception exp)
{
throw exp;
}
return true;
}
#endregion
#endregion
/// <summary>
/// 獲取Excel文件數據表列表
/// </summary>
public static ArrayList GetExcelTables(string ExcelFileName)
{
DataTable dt = new DataTable();
ArrayList TablesList = new ArrayList();
if (File.Exists(ExcelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))
{
try
{
conn.Open();
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
}
catch (Exception exp)
{
throw exp;
}
//獲取數據表個數
int tablecount = dt.Rows.Count;
for (int i = 0; i < tablecount; i++)
{
string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');
if (TablesList.IndexOf(tablename) < 0)
{
TablesList.Add(tablename);
}
}
}
}
return TablesList;
}
/// <summary>
/// 將Excel文件導出至DataTable(第一行做爲表頭)
/// </summary>
/// <param name="ExcelFilePath">Excel文件路徑</param>
/// <param name="TableName">數據表名,若是數據表名錯誤,默認爲第一個數據表名</param>
public static DataTable InputFromExcel(string ExcelFilePath, string TableName)
{
if (!File.Exists(ExcelFilePath))
{
throw new Exception("Excel文件不存在!");
}
//若是數據表名不存在,則數據表名爲Excel文件的第一個數據表
ArrayList TableList = new ArrayList();
TableList = GetExcelTables(ExcelFilePath);
if (TableName.IndexOf(TableName) < 0)
{
TableName = TableList[0].ToString().Trim();
}
DataTable table = new DataTable();
OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0");
OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
try
{
if (dbcon.State == ConnectionState.Closed)
{
dbcon.Open();
}
adapter.Fill(table);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (dbcon.State == ConnectionState.Open)
{
dbcon.Close();
}
}
return table;
}
/// <summary>
/// 獲取Excel文件指定數據表的數據列表
/// </summary>
/// <param name="ExcelFileName">Excel文件名</param>
/// <param name="TableName">數據表名</param>
public static ArrayList GetExcelTableColumns(string ExcelFileName, string TableName)
{
DataTable dt = new DataTable();
ArrayList ColsList = new ArrayList();
if (File.Exists(ExcelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))
{
conn.Open();
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, TableName, null });
//獲取列個數 int colcount = dt.Rows.Count; for (int i = 0; i < colcount; i++) { string colname = dt.Rows[i]["Column_Name"].ToString().Trim(); ColsList.Add(colname); } } } return ColsList; }}