日期:2014-05-18  浏览次数:20429 次

我想将网页的数据导出到一个固定格式的Excel表中,应该怎么操作呢?
说白了,就是如何控制数据写入Excel指定的单元格?Excel中已经有固定表,只需要向表中的相关单元格填写数据就行了。
而不需要一股脑将网页所有数据都横七竖八的写到Excel中,谢谢。

------解决方案--------------------
Response.Clear();
Response.Buffer = true;
Response.Charset = "gb2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=users.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); 
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
------解决方案--------------------
public string DataTableToExcel(DataTable dt,string excelPath) 

if(dt == null) 

return "DataTable不能为空"; 


int rows = dt.Rows.Count; 
int cols = dt.Columns.Count; 
StringBuilder sb; 
string connString; 

if(rows == 0) 

return "没有数据"; 


sb = new StringBuilder(); 
connString = string.Format(ConnectionString,excelPath); 

//生成创建表的脚本 
sb.Append("CREATE TABLE "); 
sb.Append(dt.TableName + " ( "); 

for(int i=0;i { 
if(i < cols - 1) 
sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName)); 
else 
sb.Append(string.Format("{0} varchar)",dt.Columns[i].ColumnName)); 


using(OleDbConnection objConn = new OleDbConnection(connString)) 

OleDbCommand objCmd = new OleDbCommand(); 
objCmd.Connection = objConn; 

objCmd.CommandText = sb.ToString(); 

try 

objConn.Open(); 
objCmd.ExecuteNonQuery(); 

catch(Exception e) 

return "在Excel中创建表失败,错误信息:" + e.Message; 


生成插入数据脚本#region 生成插入数据脚本 
sb.Remove(0,sb.Length); 
sb.Append("INSERT INTO "); 
sb.Append(dt.TableName + " ( "); 

for(int i=0;i { 
if(i < cols - 1) 
sb.Append(dt.Columns[i].ColumnName + ","); 
else 
sb.Append(dt.Columns[i].ColumnName + ") values ("); 


for(int i=0;i { 
if(i < cols - 1) 
sb.Append("@" + dt.Columns[i].ColumnName + ","); 
else 
sb.Append("@" + dt.Columns[i].ColumnName + ")"); 

#endregion 


//建立插入动作的Command 
objCmd.CommandText = sb.ToString(); 
OleDbParameterCollection param = objCmd.Parameters; 

for(int i=0;i { 
param.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, OleDbType.VarChar)); 


//遍历DataTable将数据插入新建的Excel文件中 
foreach (DataRow row in dt.Rows) 

for (int i=0; i { 
param[i].Value = row[i]; 


objCmd.ExecuteNonQuery(); 


return "数据已成功导入Excel"; 
}//end using