这是一个使用Excel中查询分析器(Ms通用查询分析器)完成从 SQL Server 7.0以上版本(已通过测试)的数据快速导出到Excel中的示例。它由两个参数完成,其中的第一个是你所要进行查询分析时使用的Select查询语句。 为了好看,我们给我们导出的数据加上一个名称。名称,由第二个参数传递进来:)好了,不说什么废话了。大家看代码吧。
using System; using Excel; namespace 类库 { public class Excel导出 { public Excel导出(string 查询语句,string 标题) { Excel.Application excel; Excel._Workbook xBk; Excel._Worksheet xSt; Excel._QueryTable xQt; string Conn = “ODBC;DRIVER=SQL Server;SERVER=[服务器地址或者名称];UID=sa;PWD=[密码];APP=[应用程序名称(一般为操作系统名)];WSID=[工 作站名称(客户端)];DATABASE=[数据库名称]”; string Select = 查询语句; excel = new Excel.ApplicationClass(); xBk = excel.Workbooks.Add(true); xSt = (Excel._Worksheet)xBk.ActiveSheet; excel.Cells[2,2] = 标题; xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true; xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Name = “黑体”; xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22; xQt = xSt.QueryTables.Add(Conn,xSt.get_Range(excel.Cells[4,2],excel.Cells[4,2]),Select); xQt.Name = “导出示例”; xQt.FieldNames = true; xQt.RowNumbers = false; xQt.FillAdjacentFormulas = false; xQt.PreserveFormatting = false; xQt.BackgroundQuery = true; xQt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertDeleteCells; xQt.AdjustColumnWidth = true; xQt.RefreshPeriod = 0; xQt.PreserveColumnInfo = true; xQt.Refresh(xQt.BackgroundQuery); excel.Visible = true; } } }
全中文的,不用进行解释了吧?
原来进行数据导出操作(相关连接http://www.csdn.net/Develop/Read_Article.asp?Id=21391), 三百条记录,用时十分钟以上。如果使用Excel自带的这一个查询工具,导出一万条记录,只需十秒钟以内的时间,而且,可以完成格式自动排版的功能。
可能有人会问:Excel里面的查询语句与SQL Server里面的查询语句是不是一样的?这里说明一点。使用这个类,可以直接使用SQL Server里面的查询语句,包括直接传递SQL Server的存储过程。