VBA ADO輸出到CSV 注意細節

2021-10-01 22:53:34 字數 2542 閱讀 1825

方法一:逐行輸出

sub 將查詢結果儲存為csv ()

if checkbox1.value = true then

tex = "a.eutrancellfdd"

elseif checkbox2.value = true then

tex = "a.eutrancelltdd"

end if

dim cnn, sql$, a, b, c, d, e, f, g, h, i, l, m

set cnn = createobject("adodb.connection")

set rs = createobject("adodb.recordset")

cnn.open "provider = microsoft.ace.oledb.12.0;extended properties =text;data source =" & thisworkbook.path & "\"

sql = "select erbs," & tex & " as cell,(iif(instr(" & tex & ",'d-')>0,'tdd d',iif(instr(" & tex & ",'f-')>0,'tdd f',iif(instr(" & tex & ",'gs-')>0,'fdd900',iif(instr(" & tex & ",'dc-')>0,'fdd1800',iif(instr(" & tex & ",'a-')>0,'tdd a','tdd e')))))) as 頻段 from [kpi.csv] a group by " & tex & ",erbs"

set rs = cnn.execute(sql)

arr = cnn.execute(sql).getrows

brr = rs.fields.count 'rs.fields.count

open thisworkbook.path & "\小區列表.csv" for output as #1

print #1, rs.fields(0).name + chr(44) + rs.fields(1).name + chr(44) + rs.fields(2).name

for j = 0 to ubound(arr, 2) '列數

'for l = 0 to brr - 1

print #1, arr(0, j) + chr(44) + arr(1, j) + chr(44) + arr(2, j)

next

close #1

rs.close

cnn.close

set rst = nothing

set cnn = nothing

worksheets("結果").activate

msgbox ("ok")

end sub

方法二:按行(細節決定成敗)

set cnn = createobject("adodb.connection")

set rs = createobject("adodb.recordset")

cnn.mode = admodereadwrite

cnn.open "provider=microsoft.ace.oledb.12.0;extended properties=""text;hdr=yes;fmt=delimited(,)"";data source=" & thisworkbook.path & "\"

sql = "select replace(ip,'.log','') as ip,eutrancell,eutranfreqrelation,eutrancellrelation,cellindividualoffseteutran,ishoallowed,qoffsetcelleutran,[loadbalancing(0:not_allowed/1:allowed)],[scellcandidate(1:allowed/2:auto)] from [eutrancellrelation.csv]"

set rs = cnn.execute(sql) '將sql語句獲得的資料傳

open thisworkbook.path & "\output.csv" for output as #1

for m = 0 to rs.fields.count - 1

print #1, rs.fields(m).name + chr(44);

next

print #1, '\n'

arr = cnn.execute(sql).getrows

brr = rs.fields.count 'rs.fields.count

for j = 0 to ubound(arr, 2) '列數

for l = 0 to brr - 1

print #1, arr(l, j) + chr(44); '''';分號表示不換行

next

print #1, '\n'

next

close #1

cnn.close

set rst = nothing

set cnn = nothing

msgbox "ok"

arcpy 讀寫csv 字段屬性輸出到csv文件

coding gbk import csvimport arcpy defmain 讀取 csv path r e 2 learning course arcpy高階 arcpy 4 文字讀寫 csv test.csv csv file open csv path,r csv reader csv....

利用VBA ADO轉置及合併CSV

sub 轉置 transfrom 統計項 select 行欄位 from 資料來源 group by 列欄位 pivot 行欄位 set cnn createobject adodb.connection set rs createobject adodb.recordset cnn.open pr...

解決python 輸出到csv 出現多空行的情況

這個問題的解決方案網上挺多的。with open r f desktop book3程式設計客棧.csv w encoding gb18030 newline as cwf spamwriter csv.writer cwf sp程式設計客棧amwriter.writerow 劇名 主要演員 上映時...