简体   繁体   English

Excel:将查询结果直接保存到CSV文件

[英]Excel: Saving query results directly to CSV file

I have a dataset in Excel, of which I have to save an assorted part to a new csv file. 我在Excel中有一个数据集,其中的一个数据集必须保存到新的csv文件中。 I have used SQL to select the part required to be saved. 我已使用SQL选择需要保存的部分。 I was hoping somebody would guide me about saving this selection to csv using SQL. 我希望有人会指导我有关使用SQL将选择的内容保存到csv。

SQL gives me a recordset but I would like to loop through it only as a last resort. SQL给了我一个记录集,但我只想作为最后的方法遍历它。 I am hoping there is a better approach that directly saves the entire result from within the query itself if possible. 我希望有一种更好的方法,如果可能的话,可以直接从查询本身内部保存整个结果。

Something like the solution by Remou on Want VBA in excel to read very large CSV and create output file of a small subset of the CSV is what I'm looking for. 我正在寻找类似于Remou 在Excel中的Want VBA上的解决方案,该方案可读取非常大的CSV并创建一小部分CSV的输出文件 But unfortunately I can't get that to work. 但不幸的是,我无法使它正常工作。

Assuming you are in Excel VBA, has an ADODB opened with a Recordset object connected to a database and you want to save the content into a CSV (from within the Excel VBA). 假设您在Excel VBA中,已打开一个ADODB,并且Recordset对象已连接到数据库,并且您想将内容保存到CSV中(从Excel VBA中)。

The easiest is actually still by looping through the records in the recordset. 实际上,最简单的方法仍然是遍历记录集中的记录。

However, since you already rule that out (for whatever reasons), the next option would be to use the Recordset.Save <StreamObject> method. 但是,由于您已经排除了这种情况(无论出于何种原因),因此下一个选择是使用Recordset.Save <StreamObject>方法。 Create a System.IO.Streamwriter object to pass to the Recordset.Save . 创建一个System.IO.Streamwriter对象传递给Recordset.Save

OR, another way if you are using Jet SQL is: 或者,使用Jet SQL的另一种方法是:

conDB.Execute "SELECT * INTO [Text;Database=" _
               & vsCSVFolder _
               & ";HDR=No;FMT=Delimited].[" _
               & vsCSVFileame _
               & "] FROM Attendance", _
                 DBExport, _
                 adCmdText Or adExecuteNoRecords

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM