转载 用excel的QueryTable来直接查询数据库生成Excel

原文位于:http://topic.csdn.net/u/20080805/14/A6F56D54-E009-4DCE-99C6-C27CE40DD4A5.html

 

说明:需要加入此com组件Microsoft Excel 11.0 Object Library参考

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication18
{
   
class Program
    {
       
static void Main(string[] args)
        {
            ExportDataToExcel(
"Provider=SQLOLEDB.1;sever=localhost;uid=sa;password=***;database=master;",
               
"select * from sysobjects",@"c:\testOle.xls","sysobjects");
        }
       
/// <summary>
       
/// 直接导出数据到excel
       
/// </summary>
       
/// <param name="connectionString">连接字符串</param>
       
/// <param name="sql">查询语句</param>
       
/// <param name="fileName">文件名</param>
       
/// <param name="sheetName">表名</param>
        static void ExportDataToExcel(string connectionString,string sql,string fileName,string sheetName)
        {
            Excel.Application app
= new Excel.ApplicationClass();
            Excel.Workbook wb
= (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
            Excel.Worksheet ws
= wb.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
            ws.Name
= sheetName;
           
try
            {
                Excel.QueryTable qt
= ws.QueryTables.Add("OLEDB;" + connectionString,
                    ws.get_Range(
"A1", Missing.Value), sql);
                qt.Refresh(
false);//是否异步查询
            }
           
catch (Exception ex)
            {
               
string str = ex.Message;
            }
           
finally
            {
                wb.Saved
= true;
                wb.SaveCopyAs(fileName);
//保存
                app.Quit();//关闭进程
            }
        }
    }
}

posted on 2008-08-09 08:48  Good life  阅读(612)  评论(0编辑  收藏  举报