用ADO向Excel批量导入数据

和前面一篇用OleDB的方法类似,我们可以用ADO从RecordSet对象向Excel批量插入数据,这个方法无法自动复制字段名。
我们需要引用ADO和Excel的com对象
用ADO向Excel批量导入数据
用ADO向Excel批量导入数据

参考代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. using Excel=Microsoft.Office.Interop.Excel;
  6. namespace ConsoleApplication18
  7. {
  8. class Program
  9. {
  10. static void Main( string []args)
  11. {
  12. ExportDataToExcel( "server=(local);uid=sa;pwd=sqlgis;database=master" ,
  13. "select*fromsysobjects" ,@ "c:\testADO.xls" , "sysobjects" );
  14. }
  15. static void ExportDataToExcel( string connectionString, string sql, string fileName, string sheetName)
  16. {
  17. Excel.Applicationapp= new Excel.ApplicationClass();
  18. Excel.Workbookwb=(Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
  19. Excel.Worksheetws=wb.Worksheets.Add(Missing.Value,Missing.Value,Missing.Value,Missing.Value) as Excel.Worksheet;
  20. ws.Name=sheetName;
  21. try
  22. {
  23. ADODB.Connectionconn= new ADODB.ConnectionClass();
  24. conn.Open( "driver={SQLServer};" +connectionString, "" , "" ,0);
  25. ADODB.Recordsetrs= new ADODB.RecordsetClass();
  26. rs.Open(sql,conn,ADODB.CursorTypeEnum.adOpenStatic,ADODB.LockTypeEnum.adLockReadOnly,0);
  27. Excel.Rangerange=ws.get_Range( "A2" ,Missing.Value);
  28. range.CopyFromRecordset(rs,65535,65535);
  29. }
  30. catch (Exceptionex)
  31. {
  32. string str=ex.Message;
  33. }
  34. finally
  35. {
  36. wb.Saved= true ;
  37. wb.SaveCopyAs(fileName); //保存
  38. app.Quit(); //关闭进程
  39. }
  40. }
  41. }
  42. }

相关文章:
用QueryTable向excel批量导入数据

你可能感兴趣的:(sql,sql,server,Excel,Microsoft,Office)