首頁 資料庫 mysql教程 从T-SQL中创建Excel的XLS格式文件

从T-SQL中创建Excel的XLS格式文件

Jun 07, 2016 pm 02:54 PM
excel xls 創建 文件 格式

从T-SQL中创建Excel的XLS格式文件 T-SQL Excel XLS Create Excel XLS from T-SQLScript Rating Total number of votes [30] By: David A. Long This is a T-SQL script that uses OLE, ADO, Jet4 ISAM, and Linked Server to create and populate an Excel Wo

从T-SQL中创建Excel的XLS格式文件 T-SQL Excel XLS
Create Excel XLS from T-SQL
Script Rating        Total number of votes [30] 
By: David A. Long 
This is a T-SQL script that uses OLE, ADO, Jet4 ISAM, and Linked Server to create and populate an Excel Workbook (XLS) file from T-SQL query. If the Excel Worksheet exists, the query will append to the "table". 
The code is designed to be used by SQL Agent and to append to the step output with verbose and minimal detail. 
Code is pretty well commented, including some hard won knowledge about Jet4 ISAM, OLE, ADO, and usage of the Excel table from T-SQL
-- Create XLS script DAL - 04/24/2003
--
-- Designed for Agent scheduling, turn on "Append output for step history"
--
-- Search for %%% to find adjustable constants and other options
--
-- Uses OLE for ADO and OLE DB to create the XLS file if it does not exist
--   Linked server requires the XLS to exist before creation
-- Uses OLE ADO to Create the XLS Worksheet for use as a table by T-SQL
-- Uses Linked Server to allow T-SQL access to XLS table
-- Uses T-SQL to populate te XLS worksheet, very fast
--
PRINT 'Begin CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
PRINT ''
GO 

SET NOCOUNT ON
DECLARE @Conn int -- ADO Connection object to create XLS
 , @hr int -- OLE return value
 , @src varchar(255) -- OLE Error Source
 , @desc varchar(255) -- OLE Error Description
 , @Path varchar(255) -- Drive or UNC path for XLS
 , @Connect varchar(255) -- OLE DB Connection string for Jet 4 Excel ISAM
 , @WKS_Created bit -- Whether the XLS Worksheet exists
 , @WKS_Name varchar(128) -- Name of the XLS Worksheet (table)
 , @ServerName nvarchar(128) -- Linked Server name for XLS
 , @DDL varchar(8000) -- Jet4 DDL for the XLS WKS table creation
 , @SQL varchar(8000) -- INSERT INTO XLS T-SQL
 , @Recs int -- Number of records added to XLS
 , @Log bit -- Whether to log process detail

-- Init variables
SELECT @Recs = 0
 -- %%% 1 = Verbose output detail, helps find problems, 0 = minimal output detail
 , @Log = 1 
-- %%% assign the UNC or path and name for the XLS file, requires Read/Write access
--   must be accessable from server via SQL Server service account
--   & SQL Server Agent service account, if scheduled
SET @Path = 'C:\TEMP\Test_'+CONVERT(varchar(10),GETDATE(),112)+'.xls'
-- assign the ADO connection string for the XLS creation
SET @Connect = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+@Path+';Extended Properties=Excel 8.0'
-- %%% assign the Linked Server name for the XLS population
SET @ServerName = 'EXCEL_TEST'
-- %%% Rename Table as required, this will also be the XLS Worksheet name
SET @WKS_Name = 'People'
-- %%% Table creation DDL, uses Jet4 syntax, 
--   Text data type = varchar(255) when accessed from T-SQL
SET @DDL = 'CREATE TABLE '+@WKS_Name+' (SSN Text, Name Text, Phone Text)'
-- %%% T-SQL for table population, note the 4 part naming required by Jet4 OLE DB
--   INSERT INTO SELECT, INSERT INTO valueS, and EXEC sp types are supported
--   Linked Server does not support SELECT INTO types
SET @SQL = 'INSERT INTO '+@ServerName+'...'+@WKS_Name+' (SSN, Name, Phone) '
SET @SQL = @SQL+'SELECT au_id AS SSN'
SET @SQL = @SQL+', LTRIM(RTRIM(ISNULL(au_fname,'''')+'' ''+ISNULL(au_lname,''''))) AS Name'
SET @SQL = @SQL+', phone AS Phone '
SET @SQL = @SQL+'FROM pubs.dbo.authors'

IF @Log = 1 PRINT 'Created OLE ADODB.Connection object'
-- Create the Conn object
EXEC @hr = sp_OACreate 'ADODB.Connection', @Conn OUT
IF @hr <> 0 -- have to use <> as OLE / ADO can return negative error numbers
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT 
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT char(9)+'Assigned ConnectionString property'
-- Set a the Conn object's ConnectionString property
--   Work-around for error using a variable parameter on the Open method
EXEC @hr = sp_OASetProperty @Conn, 'ConnectionString', @Connect
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT 
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT char(9)+'Open Connection to XLS, for file Create or Append'
-- Call the Open method to create the XLS if it does not exist, can't use parameters
EXEC @hr = sp_OAMethod @Conn, 'Open'
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT 
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

-- %%% This section could be repeated for multiple Worksheets (Tables)
IF @Log = 1 PRINT char(9)+'Execute DDL to create '''+@WKS_Name+''' worksheet'
-- Call the Execute method to Create the work sheet with the @WKS_Name caption, 
--   which is also used as a Table reference in T-SQL
-- Neat way to define column data types in Excel worksheet
--   Sometimes converting to text is the only work-around for Excel's General 
--   Cell formatting, even though the Cell contains Text, Excel tries to format
--   it in a "Smart" way, I have even had to use the single quote appended as the
--   1st character in T-SQL to force Excel to leave it alone
EXEC @hr = sp_OAMethod @Conn, 'Execute', NULL, @DDL, NULL, 129 -- adCmdText + adExecuteNoRecords
-- 0x80040E14 for table exists in ADO
IF @hr = 0x80040E14 
 -- kludge, skip 0x80042732 for ADO Optional parameters (NULL) in SQL7
 OR @hr = 0x80042732
BEGIN
 -- Trap these OLE Errors
 IF @hr = 0x80040E14
 BEGIN
  PRINT char(9)+''''+@WKS_Name+''' Worksheet exists for append'
  SET @WKS_Created = 0
 END
 SET @hr = 0 -- ignore these errors
END
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT 
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

IF @Log = 1 PRINT 'Destroyed OLE ADODB.Connection object'
-- Destroy the Conn object, +++ important to not leak memory +++
EXEC @hr = sp_OADestroy @Conn
IF @hr <> 0
BEGIN
 -- Return OLE error
 EXEC sp_OAGetErrorInfo @Conn, @src OUT, @desc OUT 
 SELECT Error=convert(varbinary(4),@hr), Source=@src, Description=@desc
 RETURN
END

-- Linked Server allows T-SQL to access the XLS worksheet (Table)
--   This must be performed after the ADO stuff as the XLS must exist
--   and contain the schema for the table, or worksheet
IF NOT EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
 IF @Log = 1 PRINT 'Created Linked Server '''+@ServerName+''' and Login'
 EXEC sp_addlinkedserver @server = @ServerName
      , @srvproduct = 'Microsoft Excel Workbook'
      , @provider = 'Microsoft.Jet.OLEDB.4.0'
      , @datasrc = @Path
      , @provstr = 'Excel 8.0' 
 -- no login name or password are required to connect to the Jet4 ISAM linked server
 EXEC sp_addlinkedsrvlogin @ServerName, 'false' 
END

-- Have to EXEC the SQL, otherwise the SQL is evaluated 
--   for the linked server before it exists
EXEC (@SQL)
PRINT char(9)+'Populated '''+@WKS_Name+''' table with '+CONVERT(varchar,@@ROWCOUNT)+' Rows'

-- %%% Optional you may leave the Linked Server for other XLS operations
--   Remember that the Linked Server will not create the XLS, so remove it
--   When you are done with it, especially if you delete or move the file
IF EXISTS(SELECT srvname from master.dbo.sysservers where srvname = @ServerName)
BEGIN
 IF @Log = 1 PRINT 'Deleted Linked Server '''+@ServerName+''' and Login'
 EXEC sp_dropserver @ServerName, 'droplogins'
END
GO

SET NOCOUNT OFF
PRINT ''
PRINT 'Finished CreateXLS script at '+RTRIM(CONVERT(varchar(24),GETDATE(),121))+' '
GO
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

excel列印表格框線消失怎麼辦 excel列印表格框線消失怎麼辦 Mar 21, 2024 am 09:50 AM

如果在開啟一份需要列印的文件時,在列印預覽裡我們會發現表格框線不知為何消失不見了,遇到這樣的情況,我們就要及時進行處理,如果你的列印文件裡也出現了此類的問題,那麼就和小編一起來學習下邊的課程吧:excel列印表格框線消失怎麼辦? 1.開啟一份需要列印的文件,如下圖所示。  2、選取所有需要的內容區域,如下圖所示。  3、按滑鼠右鍵,選擇「設定儲存格格式」選項,如下圖所示。  4、點選視窗上方的「邊框」選項,如下圖所示。  5、在左側的線條樣式中選擇細實線圖樣,如下圖所示。  6、選擇“外邊框”

excel同時篩選3個以上關鍵字怎麼操作 excel同時篩選3個以上關鍵字怎麼操作 Mar 21, 2024 pm 03:16 PM

在日常辦公中經常使用Excel來處理數據,時常遇到需要使用「篩選」功能。當我們在Excel中選擇執行「篩選」時,對於同一列而言,最多只能篩選兩個條件,那麼,你知道excel同時篩選3個以上關鍵字該怎麼操作嗎?接下來,就請小編為大家示範一次。第一種方法是將條件逐步加入篩選器。如果要同時篩選出三個符合條件的明細,首先需要逐步篩選出其中一個。開始時,可以先依照條件篩選出姓「王」的員工。然後按一下【確定】,接著在篩選結果中勾選【將目前所選內容新增至篩選器】。操作步驟如下圖所示。  同樣,再次分別執行篩選

excel表格相容模式改正常模式的方法 excel表格相容模式改正常模式的方法 Mar 20, 2024 pm 08:01 PM

在我們日常的工作學習中,從他人處拷貝了Excel文件,打開進行內容添加或重新編輯後,再保存的有時候,有時會提示出現兼容性檢查的對話框,非常的麻煩,不知道Excel軟體,可不可改為正常模式呢?那麼下面就由小編為大家帶來解決這個問題的詳細步驟,讓我們一起來學習吧。最後一定記得收藏保存。 1.開啟一個工作表,在工作表的名稱中顯示多出來一個相容模式,如圖所示。 2.在這個工作表中,進行了內容的修改後保存,結果總是彈出兼容檢查器的對話框,很麻煩看見這個頁面,如圖所示。  3、點選Office按鈕,點另存為,然

excel上標應該如何設定 excel上標應該如何設定 Mar 20, 2024 pm 04:30 PM

在處理資料時,有時我們會遇到資料包含了倍數、溫度等等各種符號的時候,你知道excel上標應該如何設定嗎?我們在使用excel處理資料時,如果不會設定上標,這可是會讓我們的許多資料在輸入時就會比較麻煩。今天小編就為大家帶來了excel上標的具體設定方法。 1.首先,讓我們打開桌面上的MicrosoftOfficeExcel文檔,選擇需要修改為上標的文字,具體如圖所示。 2.然後,點擊右鍵,點擊後出現的選單中,選擇「設定儲存格格式」選項,具體如圖所示。 3.接下來,在系統自動彈出的「儲存格格式」對話框

出現0x80004005錯誤代碼怎麼辦 小編教你0x80004005錯誤代碼解決方法 出現0x80004005錯誤代碼怎麼辦 小編教你0x80004005錯誤代碼解決方法 Mar 21, 2024 pm 09:17 PM

在電腦中刪除或解壓縮資料夾,時有時會彈出提示對話框“錯誤0x80004005:未指定錯誤”,如果遇到這中情況應該怎麼解決呢?提示錯誤碼0x80004005的原因其實很多,但大部分因為病毒導致,我們可以重新註冊dll來解決問題,下面,小編給大夥講解0x80004005錯誤代碼處理經驗。有使用者在使用電腦時出現錯誤代碼0X80004005的提示,0x80004005錯誤主要是由於電腦沒有正確註冊某些動態連結庫文件,或電腦與Internet之間存在不允許的HTTPS連接防火牆所引起。那麼如何

excel中iif函數的用法 excel中iif函數的用法 Mar 20, 2024 pm 06:10 PM

大部分使用者使用Excel都是用來處理表格資料的,其實Excel還有vba程式編寫,這個除了專人士應該沒有多少使用者用過此功能,在vba編寫時常常會用到iif函數,它其實跟if函數的功能差不多,下面小編跟大家介紹下iif函數的用法。 Excel中SQL語句和VBA程式碼中都有iif函數。 iif函數和excel工作表中的IF函數用法相似,執行真假值判斷,根據邏輯計算的真假值,傳回不同結果。 IF函數用法是(條件,是,否)。 VBA中的IF語句和IIF函數,前者IF語句是控制語句可以依照條件執行不同的語句,後者

excel閱讀模式在哪裡設置 excel閱讀模式在哪裡設置 Mar 21, 2024 am 08:40 AM

在軟體的學習中,我們習慣用excel,不僅是因為需要方便,更因為它可以滿足多種實際工作中需要的格式,而且excel運用起來非常的靈活,有種模式是方便閱讀的,今天帶給大家的就是:excel閱讀模式在哪裡設定。 1.開啟電腦,然後再開啟Excel應用,找到目標資料。 2.要想在Excel中,設定閱讀模式,有兩種方式。第一種:Excel中,有大量的便利處理方式,分佈在Excel中佈局中。在Excel的右下角,有設定閱讀模式的快捷方式,找到十字標誌的圖案,點擊即可進入閱讀模式,在十字標誌的右邊有一個小的三

PPT幻燈片插入excel圖示的操作方法 PPT幻燈片插入excel圖示的操作方法 Mar 26, 2024 pm 05:40 PM

1.開啟PPT,翻頁至需要插入excel圖示的頁面。點選插入選項卡。 2、點選【對象】。 3、跳出以下對話框。 4.點選【由檔案建立】,點選【瀏覽】。 5、選擇需要插入的excel表格。 6.點選確定後跳出如下頁面。 7.勾選【顯示為圖示】。 8.點選確定即可。

See all articles