public string DataTableToExcel(DataTable dt,string ExcelPath)
{
if(dt == null)
{
return "DataTable不能為空";
}
int rows = dt.Rows.Count;
int cols = dt.Columns.Count;
StringBuilder sb;
string connString;
if(rows == 0)
{
return "沒有數據";
}
sb = new StringBuilder();
connString = string.Format(ConnectionString,ExcelPath);
//生成創建表的腳本
sb.Append("CREATE TABLE ");
sb.Append(dt.TableName + " ( ");
for(int i=0;i<cols;i++)
{
if(i < cols - 1)
sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName));
else
sb.Append(string.Format("{0} varchar)",dt.Columns[i].ColumnName));
}
using(OleDbConnection objConn = new OleDbConnection(connString))
{
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = objConn;
objCmd.CommandText = sb.ToString();
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
}
catch(Exception e)
{
return "在Excel中創建表失敗,錯誤信息:" + e.Message;
}
生成插入數據腳本#region 生成插入數據腳本
sb.Remove(0,sb.Length);
sb.Append("INSERT INTO ");
sb.Append(dt.TableName + " ( ");
for(int i=0;i<cols;i++)
{
if(i < cols - 1)
sb.Append(dt.Columns[i].ColumnName + ",");
else
sb.Append(dt.Columns[i].ColumnName + ") values (");
}
for(int i=0;i<cols;i++)
{
if(i < cols - 1)
sb.Append("@" + dt.Columns[i].ColumnName + ",");
else
sb.Append("@" + dt.Columns[i].ColumnName + ")");
}
#endregion
//建立插入動作的Command
objCmd.CommandText = sb.ToString();
OleDbParameterCollection param = objCmd.Parameters;
for(int i=0;i<cols;i++)
{
param.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, OleDbType.VarChar));
}
//遍歷DataTable將數據插入新建的Excel文件中
foreach (DataRow row in dt.Rows)
{
for (int i=0; i<param.Count; i++)
{
param[i].Value = row[i];
}
objCmd.ExecuteNonQuery();
}
return "數據已成功導入Excel";
}//end using
}