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;
}
}
}
}