将SqlServer的数据导出到Excel/csv中的各种方法 .
以下都只是介紹操作的原理,具體要求要在應(yīng)用中具體分析改變。
如果大家有其他好的方法,請相互告知,共同學(xué)習(xí)。
?
1.?????? 此方法常用在form或者Console Application中,使用時須用要添加Reference,具體做法:
???????? ?右鍵點擊項目添加“Add Reference”,在com組件下,選擇“Microsoft Excel 14.0 Object Library”,然后在項目中使用?????
??????? ?下面注釋//it looks like excele table start with 1 not 1
??????? ? 應(yīng)該為//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 columnsfor (int i = 0; i < dt.Columns.Count;i++ ){//here is started with 1//it looks like excele table start with 1 not 1excel.Cells[1, i + 1] = dt.Columns[i].ColumnName.ToString(); }//get the data in rowsfor (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應(yīng)用中,可通過HttpContext.Response.write()來實現(xiàn)
?
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提供的一個快捷的數(shù)據(jù)導(dǎo)入導(dǎo)出工具。使用它不需要啟動任何圖形管理工具就能以高效的方式導(dǎo)入導(dǎo)出數(shù)據(jù)。bcp是SQL Server中負責(zé)導(dǎo)入導(dǎo)出數(shù)據(jù)的一個命令行工具,它是基于DB-Library的,并且能以并行的方式高效地導(dǎo)入導(dǎo)出大批量的數(shù)據(jù)。bcp可以將數(shù)據(jù)庫的表或視圖直接導(dǎo)出,也能通過SELECT FROM語句對表或視圖進行過濾后導(dǎo)出。在導(dǎo)入導(dǎo)出數(shù)據(jù)時,可以使用默認值或是使用一個格式文件將文件中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫或?qū)?shù)據(jù)庫中的數(shù)據(jù)導(dǎo)出到文件中.
use swangtest GoSP_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 '?
?
??
轉(zhuǎn)載于:https://www.cnblogs.com/songsz1/archive/2012/09/05/2671346.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的将SqlServer的数据导出到Excel/csv中的各种方法 .的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。