此段代碼是針對DataTable 對xml、excel、csv 對文件的導入和導出功能,記錄一下,以供以後使用。
一定要導入excel 並添加引用Microsoft.Office.Interop.Excel 11.0版本。
Default.aspx.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
namespace fantest
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Bind();
}
protected void Bind()
{
this.GridView1.DataSource = this.GetDataTable();
this.GridView1.DataBind();
}
private DataTable GetDataTable()
{
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123456;database=test"))
{
string sql = "select * from InfoTable where 1=1";
SqlDataAdapter dap = new SqlDataAdapter(sql, conn);
dap.Fill(ds,"InfoTable");
}
return ds.Tables["InfoTable"];
}
//TO XML
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = this.GetDataTable();
StringBuilder sb = new StringBuilder();
sb.Append("<" + dt.TableName + ">");
foreach (DataRow row in dt.Rows)
{
sb.Append("<item>");
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append("<" + dt.Columns[i].ColumnName + ">" + row[i].ToString() + "</" + dt.Columns[i].ColumnName + ">");
}
sb.Append("</item>");
}
sb.Append("</" + dt.TableName + ">");
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=ss.xml");
Response.ContentType = "text/csv";
Response.Write(sb.ToString());
Response.End();
}
//FROM XML
protected void Button2_Click(object sender, EventArgs e)
{
string filepath = Server.MapPath("ss.xml");
if (!File.Exists(filepath))
{
Page.RegisterClientScriptBlock("msg", "<script>alert(該文件不存在!)</script>");
}
else
{
StringReader StrStream = null;
XmlTextReader Xmlrdr = null;
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filepath);
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmldoc.InnerXml)));
this.GridView2.DataSource = ds.Tables[0];
this.GridView2.DataBind();
}
catch (Exception ex)