我需要在未安装Microsoft Office的PC上使用VBScript向电子表格中添加一行。
我尝试过[Set objExcel = CreateObject("Excel.Application")
],但是由于该PC上不存在Excel,因此无法创建此对象。
有没有一种方法可以在没有Excel的情况下修改电子表格呢?
First Last
Joe Smith
Mary Jones
Sam Nelson
将以下VBScript代码复制到.vbs文件中:
Const adOpenStatic = 3
Const adLockOptimistic = 3
filename = "Test.xls"
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filename & _
";Extended Properties=Excel 8.0"
query = "Select * from [Sheet1$A1:B65535]"
Set rs = CreateObject("ADODB.Recordset")
rs.Open query, cn, adOpenStatic, adLockOptimistic
rs.AddNew
rs("First") = "George"
rs("Last") = "Washington"
rs.Update
rs.MoveFirst
Do Until rs.EOF
WScript.Echo rs.Fields("First") & " " & rs.Fields("Last")
rs.MoveNext
Loop
CSCRIPT Yourfile.vbs
Joe Smith
Mary Jones
Sam Nelson
George Washington
我知道...年以后,但今天我需要找出如何使用vbScript访问Excel电子表格而不在服务器上加载Excel。我在网上搜索并发现了您的信息很有帮助,但我仍然需要更多信息,所以我继续搜索。最后,我找到了我需要的解决方案,并想在这里分享,以防其他人遇到与我相同的问题。
我试图在Windows 2008服务器上使用vbScript访问(读/写)Excel电子表格,但我不想在我的服务器上安装Excel。 我的解决方案在这里(它使用PowerShell,但易于解密为VBS):
使用vbScript在没有安装Excel的情况下从Excel电子表格中读取
使用vbScript在没有安装Excel的情况下写入Excel电子表格
我希望这能帮助未来需要相同解决方案的人。
L8r...
UCG
这是我使用的脚本的最终版本,感谢大家的帮助。
Dim arrValue
arrValue = Array("Test","20","","I","2.25","3.9761","20","60","12","1","","1","1","1")
AddXLSRow "C:\Test.xls", "A1:N109", arrValue
Sub AddXLSRow(strSource, strRange, arrValues)
'This routine uses the data from an array to fill fields in the specified spreadsheet.
'Input strSource (String) = The Full path and filename of the spreadsheet to be used.
'Input arrValues (Array) = An array of values to be added to the spreadsheet.
Dim strConnection, conn, rs, strSQL, index
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource & ";Extended Properties=""Excel 8.0;HDR=Yes;"";"
Set conn = CreateObject("ADODB.Connection")
conn.Open strConnection
Set rs = CreateObject("ADODB.recordset")
strSQL = "SELECT * FROM " & strRange
rs.open strSQL, conn, 3,3
rs.AddNew
index = 0
For Each field In rs.Fields
If field.Type = 202 Then
field.value = arrValues(index)
ElseIffield.Type = 5 And arrValues(index) <> "" Then
field.value = CDbl(arrValues(index))
End If
If NOT index >= UBound(arrValues) Then
index = index + 1
End If
Next
rs.Update
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
如果没有安装Excel,我无法想象您如何能够更改Excel文档。
然而,如果您正在使用Excel 2007电子表格(xslx),那么您应该能够使用.NET Framework的OpenXML功能来更新内容,而无需实际安装Excel。
请点击这里获取有关Office OpenXML的更多信息。
使用EPPlus。 epplus.codeplex.com
您可以在没有安装Excel的情况下完成大多数与VSTO相同的操作。