protected void Page_Load(object sender, EventArgs e)
{
//将数据(html)导入到Excel中
Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
string filename = "导出Excel的表名";
//解决乱码问题
filename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
Response.Write("<body>");
Response.Write("<table border=1px>");
DataTable dataheader = BackDataHeader();
//导入Excel表头信息
Response.Write("<tr>");
if (dataheader != null)
{
for (int j = 0; j < dataheader.Columns.Count; j++)
{
Response.Write("<td style=\"vnd.ms-excel.numberformat:@\">" + dataheader.Rows[0][j].ToString() + "</td>");
}
}
Response.Write("</tr>");
DataTable dataitem = BackDataItem();
//导入Excel数据信息
if (dataitem != null)
{
for (int i = 0; i < dataitem.Rows.Count; i++)
{
Response.Write("<tr>");
for (int j = 0; j < dataitem.Rows.Count; j++)
{
Response.Write("<td style=\"vnd.ms-excel.numberformat:@\">" + dataitem.Rows[i][j].ToString() + "</td>");
}
Response.Write("</tr>");
}
}
Response.Write("</table>");
Response.Write("</body></html>");
Response.Flush();
Response.End();
}
//返回表头信息
public DataTable BackDataHeader()
{
DataTable dataheader = new DataTable();
for (int i = 0; i < 5; i++)
{
dataheader.Columns.Add("column" + i.ToString());
}
DataRow headerrow = dataheader.NewRow();
for (int i = 0; i < 5; i++)
{
headerrow["column" + i.ToString()] = "列名" + i.ToString();
}
dataheader.Rows.Add(headerrow);
return dataheader;
}
//返回数据信息
public DataTable BackDataItem()
{
DataTable dataitem = new DataTable();
for (int i = 0; i < 5; i++)
{
dataitem.Columns.Add("column" + i.ToString());
}
for (int i = 0; i < 5; i++)
{
DataRow itemrow = dataitem.NewRow();
for (int j = 0; j < 5; j++)
{
itemrow["column" + j.ToString()] = "数据" + j.ToString();
}
dataitem.Rows.Add(itemrow);
}
return dataitem;
}