c# DataTable针对xml、excel、csv导入和导出

此段代码是针对DataTable 对xml、excel、csv 对文件的导入和导出功能,记录一下,以供以后使用。
一定要导入excel 并添加引用Microsoft.Office.Interop.Excel 11.0版本。
Default.aspx.cs文件 

  1. Default.aspx.cs文件  
  2. using  System;  
  3. using  System.Collections.Generic;  
  4. using  System.Linq;  
  5. using  System.Web;  
  6. using  System.Web.UI;  
  7. using  System.Web.UI.WebControls;  
  8. using  System.Data.SqlClient;  
  9. using  System.Data;  
  10. using  System.Xml;  
  11. using  System.Xml.Xsl;  
  12. using  System.IO;  
  13. using  System.Data.OleDb;  
  14. using  System.Data.Odbc;  
  15. using  System.Text;  
  16. using  Excel = Microsoft.Office.Interop.Excel;  
  17. namespace  fantest  
  18. {  
  19. public  partial  class  _Default : System.Web.UI.Page  
  20. {  
  21. protected   void  Page_Load( object  sender, EventArgs e)  
  22. {  
  23. Bind();  
  24. }  
  25. protected   void  Bind()  
  26. {  
  27. this .GridView1.DataSource =  this .GetDataTable();  
  28. this .GridView1.DataBind();  
  29. }  
  30. private  DataTable GetDataTable()  
  31. {  
  32. DataSet ds = new  DataSet();  
  33. using  (SqlConnection conn =  new  SqlConnection( "server=.;uid=sa;pwd=123456;database=test" ))  
  34. {  
  35. string  sql =  "select * from InfoTable where 1=1" ;  
  36. SqlDataAdapter dap = new  SqlDataAdapter(sql, conn);  
  37. dap.Fill(ds,"InfoTable" );  
  38. }  
  39. return  ds.Tables[ "InfoTable" ];  

 

//TO XML

  1. protected   void  Button1_Click( object  sender, EventArgs e)  
  2.   {  
  3.   DataTable dt = this .GetDataTable();  
  4.   StringBuilder sb = new  StringBuilder();  
  5.   sb.Append("<"  + dt.TableName +  ">" );  
  6.   foreach  (DataRow row  in  dt.Rows)  
  7.   {  
  8.   sb.Append("<item>" );  
  9.   for  ( int  i = 0; i < dt.Columns.Count; i++)  
  10.   {  
  11.   sb.Append("<"  + dt.Columns[i].ColumnName +  ">"  + row[i].ToString() +  "</"  + dt.Columns[i].ColumnName +  ">" );  
  12.   }  
  13.   sb.Append("</item>" );  
  14.   }  
  15.   sb.Append("</"  + dt.TableName +  ">" );  
  16.   Response.ClearHeaders();  
  17.   Response.AppendHeader("Content-Disposition""attachment; filename=ss.xml" );  
  18.   Response.ContentType = "text/csv" ;  
  19.   Response.Write(sb.ToString());  
  20.   Response.End();  
  21.   } 
 

//FORM XML

  1.   protected   void  Button2_Click( object  sender, EventArgs e)  
  2.   {  
  3.   string  filepath = Server.MapPath( "ss.xml" );  
  4.   if  (!File.Exists(filepath))  
  5.   {  
  6.   Page.RegisterClientScriptBlock("msg""<mce:script type=" text/javascript"><!--  
  7. alert('该文件不存在!' )  
  8. // --></mce:script>");   
  9.   }  
  10.   else   
  11.   {  
  12.   StringReader StrStream = null ;  
  13.   XmlTextReader Xmlrdr = null ;  
  14. try   
  15.   {  
  16.   XmlDocument xmldoc = new  XmlDocument();  
  17.   xmldoc.Load(filepath);  
  18.   DataSet ds = new  DataSet();  
  19.   ds.ReadXml(new  XmlTextReader( new  StringReader(xmldoc.InnerXml)));  
  20.   this .GridView2.DataSource = ds.Tables[0];  
  21.   this .GridView2.DataBind();  
  22.   }  
  23.   catch  (Exception ex)  
  24.   {  
  25.   throw  ex;  
  26.   }  
  27.   finally   
  28.   {  
  29.   if  (Xmlrdr !=  null )  
  30.   {  
  31.   Xmlrdr.Close();  
  32.   StrStream.Close();  
  33.   StrStream.Dispose();  
  34.   }  
  35.   }  
  36.   }  
  37.   } 

//TO EXCEL

  1. protected   void  Button3_Click( object  sender, EventArgs e)   
  2. {   
  3. //Response.Charset = "GB2312";    
  4. //Response.ContentEncoding = System.Text.Encoding.UTF7;    
  5. //Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("ss.xls", Encoding.UTF8).ToString());    
  6. //Response.ContentType = "application/vnd.ms-excel";    
  7. //this.EnableViewState = false;    
  8. //StringWriter tw = new StringWriter();    
  9. //HtmlTextWriter hw = new HtmlTextWriter(tw);    
  10. //this.GridView1.RenderControl(hw);    
  11. //Response.Write(tw.ToString());    
  12. //Response.End();    
  13. //上面注释的代码是一种以流的方式导入excel的,当数据在从此excel读取时会报一个异常,如果要对excel写入和读取最好用下面一种方式    
  14. DataTable dt = this .GetDataTable();   
  15. string  filepath = HttpContext.Current.Server.MapPath( "ss.xls" );   
  16. Excel.Application xlApp = new  Excel.Application();   
  17. Excel.Workbooks w= xlApp.Workbooks;   
  18. Excel.Workbook workbook = w.Add(Excel.XlWBATemplate.xlWBATWorksheet);   
  19. Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];   
  20. //写入字段    
  21. for  ( int  i = 0; i < dt.Columns.Count; i++)   
  22. {   
  23. worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;   
  24. }   
  25. //写入数值    
  26. for  ( int  r = 0; r < dt.Rows.Count; r++)   
  27. {   
  28. for  ( int  i = 0; i < dt.Columns.Count; i++)   
  29. {   
  30. worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];   
  31. }   
  32. }   
  33. worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。    
  34. workbook.Saved = true ;   
  35. workbook.SaveCopyAs(filepath);   
  36. xlApp.Quit();   
  37. GC.Collect();//强行销毁    
  38. HttpContext.Current.Response.Buffer = true ;   
  39. HttpContext.Current.Response.Clear();   
  40. HttpContext.Current.Response.ContentType = "application/ms-excel" ;   
  41. HttpContext.Current.Response.AddHeader("Content-Disposition""attachment;filename="  + HttpUtility.UrlEncode(filepath));   
  42. HttpContext.Current.Response.WriteFile(filepath);   
  43. HttpContext.Current.Response.Flush();   
  44. HttpContext.Current.Response.End();   
  45. }  

//FROM EXCEL

  1. protected   void  Button4_Click( object  sender, EventArgs e)   
  2. {   
  3. //Office 2007 连接字符串    
  4. //string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + @path + ";" + "Extended Properties=Excel 12.0;"    
  5. //Office 98-2003 连接字符串(此示例使用2003)    
  6. string  filepath = Server.MapPath( "ss.xls" );   
  7. if  (!File.Exists(filepath))   
  8. {   
  9. Page.RegisterClientScriptBlock("msg""" );   
  10. }   
  11. else    
  12. {   
  13. string  strConn =  "Provider=Microsoft.Jet.OleDb.4.0;"  +  "data source="  + filepath +  ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'" ;   
  14. OleDbConnection conn = new  OleDbConnection(strConn);   
  15. OleDbDataAdapter odda = new  OleDbDataAdapter( "select * from [Sheet1$]" , conn);   
  16. DataSet ds = new  DataSet();   
  17. odda.Fill(ds);   
  18. this .GridView2.DataSource = ds.Tables[0];   
  19. this .GridView2.DataBind();   
  20. }   
  21. }  

//TO CSV

  1. protected   void  Button5_Click( object  sender, EventArgs e)   
  2. {   
  3. DataTable dt = this .GetDataTable();   
  4. HttpContext.Current.Response.Clear();   
  5. System.IO.StringWriter sw = new  System.IO.StringWriter();   
  6. int  iColCount = dt.Columns.Count;   
  7. for  ( int  i = 0; i < iColCount; i++)   
  8. {   
  9. sw.Write("/""  + dt.Columns[i] +  "/"" );   
  10. if  (i < iColCount - 1)   
  11. {   
  12. sw.Write("," );   
  13. }   
  14. }   
  15. sw.Write(sw.NewLine);   
  16. foreach  (DataRow dr  in  dt.Rows)   
  17. {   
  18. for  ( int  i = 0; i < iColCount; i++)   
  19. {   
  20. if  (!Convert.IsDBNull(dr[i]))   
  21. sw.Write("/""  + dr[i].ToString() +  "/"" );   
  22. else    
  23. sw.Write("/"/"" );   
  24. if  (i < iColCount - 1)   
  25. {   
  26. sw.Write("," );   
  27. }   
  28. }   
  29. sw.Write(sw.NewLine);   
  30. }   
  31. sw.Close();   
  32. HttpContext.Current.Response.AddHeader("Content-Disposition""attachment; filename=ss.csv" );   
  33. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel" ;   
  34. HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312" );   
  35. HttpContext.Current.Response.Write(sw);   
  36. HttpContext.Current.Response.End();   
  37. }  

//FROM CSV

 

  1. protected   void  Button6_Click( object  sender, EventArgs e)   
  2. {   
  3. string  filepath = Server.MapPath( "ss.csv" );   
  4. if  (!File.Exists(filepath))   
  5. {   
  6. Page.RegisterClientScriptBlock("msg""" );   
  7. }   
  8. else    
  9. {   
  10. string  strConn = @ "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" ;   
  11. strConn += ";Extensions=asc,csv,tab,txt;" ;   
  12. OdbcConnection objConn = new  OdbcConnection(strConn);   
  13. DataSet ds = new  DataSet();   
  14. try    
  15. {   
  16. string  strSql =  "select * from "  + filepath;   
  17. OdbcDataAdapter odbcCSVDataAdapter = new  OdbcDataAdapter(strSql, objConn);   
  18. odbcCSVDataAdapter.Fill(ds);   
  19. this .GridView2.DataSource = ds.Tables[0];   
  20. this .GridView2.DataBind();   
  21. }   
  22. catch  (Exception ex)   
  23. {   
  24. throw  ex;   
  25. }   
  26. }   
  27. }   
  28. }   
  29. }  

Default.aspx文件:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml" >



Text="from xml" />
Text="toexcel" />
Text="fromexcel" />

Text="fromcsv" />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值