将数据导出到excel

本文介绍了一种将SQL查询结果导出到Excel文件的方法。通过C#编程实现了创建Excel表格并填充数据的过程,适用于需要将数据库内容快速分享或进行进一步处理的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using   System;  
  using   System.Data.OleDb;  
  using   System.IO;  
  using   System.Windows.Forms;  
   
  namespace   PostgraduateClient  
  {  
  ///   <summary>  
  ///   TableToExcel   的摘要说明。  
  ///   </summary>  
  public   class   SqlToExcel  
  {  
  private   string   ExcelName   ="";  
   
  public   SqlToExcel()  
  {  
  //  
  //   TODO:   在此处添加构造函数逻辑  
  //  
  }  
  public   SqlToExcel(string   tableName)  
  {  
  this.ExcelName   =tableName;  
  //  
  //   TODO:   在此处添加构造函数逻辑  
  //  
  }  
   
  public   void   ExportToExcel(string   fileName,System.Data.DataTable   DTable)  
  {  
  try  
  {  
  int   ColumnNum   =   DTable.Columns.Count;  
  string[]   ColumnNames   =   new   string[ColumnNum];  
  for(int   i=0;i<=DTable.Columns.Count-1;i++)  
  {  
  ColumnNames[i]   =   DTable.Columns[i].Caption.Trim();  
  }  
   
  string   OLEDBConnStr   =   "Provider=Microsoft.Jet.OLEDB.4.0;Data   Source="+fileName+";";        
  OLEDBConnStr   +=       "   Extended   Properties=Excel   8.0;";  
   
  string   createStr   =   "create   table   "+this.ExcelName+"(";  
  for(int   i=0;i<=DTable.Columns.Count-1;i++)  
  {  
  createStr   =   createStr   +ColumnNames[i]+"   varchar,";  
  }  
  createStr   =   createStr.Remove(createStr.Length-1,1);  
  createStr   =   createStr+")";  
   
  OleDbConnection   oConn   =   new   OleDbConnection();    
         
  oConn.ConnectionString   =   OLEDBConnStr;    
  OleDbCommand   oCreateComm   =   new   OleDbCommand();  
  oCreateComm.Connection   =   oConn;  
  oCreateComm.CommandText   =   createStr;  
   
  oConn.Open();    
  oCreateComm.ExecuteNonQuery();  
   
  //中间填充数据;  
  string   insertStr   =   "insert   into   "+this.ExcelName+"     values(";  
  for(int   i=0;i<=DTable.Rows.Count-1;i++)  
  {  
  try  
  {  
  for   (int   m=0;m<=DTable.Columns.Count-1;m++)  
  {  
  insertStr   =   insertStr   +"'"+DTable.Rows[i][m].ToString()+"',";  
  }  
  insertStr   =   insertStr.Remove(insertStr.Length-1,1)   +")";  
  oCreateComm.CommandText   =   insertStr;  
  oCreateComm.ExecuteNonQuery();  
  }  
  catch  
  {  
  MessageBox.Show("导出数据失败,请重新导出!","提示!",MessageBoxButtons.OK,MessageBoxIcon.Information);  
  return;  
  }  
  insertStr   =   "insert   into   "+this.ExcelName+"     values(";  
  }  
  //中间填充数据;  
   
  oConn.Close();  
  }  
  catch  
  {  
  MessageBox.Show("导出数据失败,请检查是否安装有Excel!或没有获得数据!","提示!",MessageBoxButtons.OK,MessageBoxIcon.Information);  
  return;  
  }  
  }  
  }  
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值