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
}
新闻热点
疑难解答
图片精选