您的位置:首页 > 产品设计 > UI/UE

.net导入Excel数据遇到问题(SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDataso)

2012-04-19 15:19 671 查看
这些天一直在做.net导入导出Excel的程序。在这里写一下过程和遇到的问题。

一 》excel导入:excel导入有多种方式,我这里用到的是sqlserver的组件'Ad Hoc Distributed Queries,具体的执行语句:select * FROM OpenDataSource ('Microsoft.Jet.OLEDB.4.0','Data Source="c:\\2012.xls"; User ID=;Password=; Extended properties=Excel 5.0')...[Sheet$]。只需要执行上面语句,就可以把excel数据导入系统,我这里的excel的结构是固定的,所以不想要太多的判断。

执行时遇到异常:“SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT 'OpenRowset/OpenDatasource' 的访问,因为此组件已作为此服务器安全配的 一 部分而被关闭。系统管理员可以通过使用 sp_configure 启用 'Ad Hoc Distributed Queries'。有关启用 'Ad Hoc Distributed Queries' 的详细信息,请参阅 SQL Server 联机丛书中的 "外围应用配置器"。”

解决办法: --启用Ad Hoc Distributed Queries:新建查询,输入

exec sp_configure 'show advanced options',1

reconfigure

exec sp_configure 'Ad Hoc Distributed Queries',1

reconfigure

--使用完成后,关闭Ad Hoc Distributed Queries:

exec sp_configure 'Ad Hoc Distributed Queries',0

reconfigure

exec sp_configure 'show advanced options',0

reconfigure

二 》excel导出:我这里用到的是bcp的导出功能,

/// <summary>

/// 根据sql语句导出excel数据

/// </summary>

/// <param name="sql"></param>

/// <param name="txtFile"></param>

/// <returns></returns>

public static string BaseDataOut( string sql, string txtFile)

{

string result = "导出成功!";

try

{

string filePath = txtFile + @"c:\test.xls";

// 导出文件

ProcessStartInfo info = new ProcessStartInfo();

info.FileName = "bcp.exe";

string s = @" "" " + sql + @" "" queryout """ + filePath + @""" -c -t -S """ + ConfigurationSettings.AppSettings["server"].Trim() + @""" -U """ + ConfigurationSettings.AppSettings["user"].Trim() + @""" -P """ + ConfigurationSettings.AppSettings["password"]
+ @"""";

string d = s;

string c = @" "" select top 1 * from test.dbo.TWMJYZBA "" queryout ""c:\t2.xls"" -c -q -S ""."" -U ""sa"" -P ""szbti@123"" ";

string f = c;

info.Arguments = @" "" " + sql + @" "" queryout """ + filePath + @""" -c -t -S """ + ConfigurationSettings.AppSettings["server"].Trim() + @""" -U """ + ConfigurationSettings.AppSettings["user"].Trim() + @""" -P """ + ConfigurationSettings.AppSettings["password"]+@"""";
//@" "" select top 1 * from test.dbo.T_WMJYZBA "" queryout ""c:\t2.xls"" -c -q -S ""."" -U ""sa"" -P ""szbti@123"" ";

info.WindowStyle = ProcessWindowStyle.Hidden;

Process proc = Process.Start(info);

proc.WaitForExit();

}

catch (Exception ex){

result = "导出出错,请联系管理员!";

}

return result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐