以下都只是介紹操作的原理,具體要求要在應用中具體分析改變。
如果大家有其他好的方法,請相互告知,共同學習。
1. 此方法常用在form或者Console Application中,使用時須用要添加Reference,具體做法:
右鍵點擊項目添加“Add Reference”,在com組件下,選擇“Microsoft Excel 14.0 Object Library”,然后在項目中使用
下面注釋//it looks like excele table start with 1 not 1
應該為//it looks like excele table start with 1 not 0
private static void exportToExcel(DataTable dt) { Excel.Application excel=new Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = true; //get the columns for (int i = 0; i < dt.Columns.Count;i++ ) { //here is started with 1 //it looks like excele table start with 1 not 1 excel.Cells[1, i + 1] = dt.Columns[i].ColumnName.ToString(); } //get the data in rows for (int row = 0; row < dt.Rows.Count;row++ ) { for (int col = 0; col < dt.Columns.Count; col++) { excel.Cells[row+2, col+1] = dt.Rows[row][dt.Columns[col]].ToString(); } } //FolderBrowserDialog path = new FolderBrowserDialog();//打開文件對話框 //path.ShowDialog(); //textBox1.Text = path.SelectedPath;//選擇文件夾 //save excel //excel.SaveWorkspace(); excel.Quit(); }
2. 在web應用中,可通過HttpContext.Response.write()來實現
protected static void toExcel(DataTable da){ System.Web.HttpContext context = System.Web.HttpContext.Current; context.Response.Clear(); foreach( DataColumn colum in da.Columns){ context.Response.Write(colum.ColumnName+"\t"); } context.Response.Write(System.Environment.NewLine); foreach (DataRow row in da.Rows) { for (int i = 0; i < da.Rows.Count; i++) { context.Response.Write(row[i].ToString()+"\t"); } context.Response.Write(System.Environment.NewLine); } context.Response.ContentType = "application/vnd.ms-excel"; context.Response.AppendHeader("Content-Disposition", "attachment; filename=plan.xls"); context.Response.End(); }
3.bcp命令是SQL Server提供的一個快捷的數據導入導出工具。使用它不需要啟動任何圖形管理工具就能以高效的方式導入導出數據。bcp是SQL Server中負責導入導出數據的一個命令行工具,它是基於DB-Library的,並且能以並行的方式高效地導入導出大批量的數據。bcp可以將數據庫的表或視圖直接導出,也能通過SELECT FROM語句對表或視圖進行過濾后導出。在導入導出數據時,可以使用默認值或是使用一個格式文件將文件中的數據導入到數據庫或將數據庫中的數據導出到文件中.
use swangtest Go SP_CONFIGURE'show advanced options',1 RECONFIGURE Go SP_CONFIGURE 'xp_cmdshell',1 RECONFIGURE Go EXEC master..xp_cmdshell 'BCP swangTest..userinfo OUT D:\entryId.csv -c -t -T '