Импортирование набора результатов запроса из SQL Server 2005 в MS Excel - PullRequest
0 голосов
/ 06 декабря 2010

Я попытался выполнить эту хранимую процедуру, предназначенную для копирования формата уже созданного листа Excel в другой лист Excel; первый служит шаблоном. Хранимая процедура предназначена для заполнения новой таблицы Excel набором результатов из запроса SQL.

При выполнении выдает следующую ошибку:

    Insert ExcelSource...[ExcelTable$]  ( A,B,C ) select convert(varchar(200),USER_ID), FIRST_NAME, 
Convert (varchar(20),CREATEDTIME) 
from SERV..AaUser
OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "ExcelSource" returned message "Cannot start your application. The workgroup information file is missing or opened exclusively by another user.".
Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "ExcelSource" reported an error. Authentication failed.
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "ExcelSource".

синтаксис хранимой процедуры:

    Create proc sp_write2Excel (@fileName varchar(100),

                                   @NumOfColumns tinyint,

                                   @query     varchar(200))

as

begin

        declare @dosStmt  varchar(200) 

        declare @tsqlStmt varchar(500) 

        declare @colList  varchar(200) 

        declare @charInd  tinyint 



        set nocount on



        -- construct the  columnList A,B,C ... 

        -- until Num Of columns is reached.



        set @charInd=0

        set @colList = 'A'

        while @charInd < @NumOfColumns - 1

        begin 

          set @charInd = @charInd + 1

          set @colList = @colList + ',' + char(65 + @charInd)

        end 



        -- Create an Empty Excel file as the target file name by copying the template Empty excel File

        set @dosStmt = ' copy C:\emp\empty.xls ' + @fileName

        exec master..xp_cmdshell @dosStmt



        -- Create a "temporary" linked server to that file in order to "Export" Data

        EXEC sp_addlinkedserver 'ExcelSource', 

        'Jet 4.0',

        'Microsoft.Jet.OLEDB.4.0',

        @fileName,

        NULL,

        'Excel 5.0'



        -- construct a T-SQL statement that will actually export the query results

        -- to the Table in the target linked server 

        set @tsqlStmt = 'Insert ExcelSource...[ExcelTable$] ' +  ' ( ' + @colList + ' ) '+ @query



        print @tsqlStmt



        -- execute dynamically the TSQL statement

        exec (@tsqlStmt)



        -- drop the linked server 

        EXEC sp_dropserver 'ExcelSource' 

        set nocount off

end 

Большое спасибо за вашу аудиторию и ожидаемую помощь.

Cheers, Tunde

1 Ответ

0 голосов
/ 07 декабря 2010

Excel установлен на том же компьютере, что и ваш экземпляр SQL Server?Существует вероятность того, что Office драйвера JET отсутствует.

Редактировать:

Я думаю, что неправильно прочитал сообщение - похоже, файл уже открыт.Файлы Excel могут быть открыты только одним пользователем одновременно, и SQL Server требует эксклюзивного доступа к этому файлу.Использование LockHunter может помочь определить, что связывает файл.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...