问题
I want to replicate the following code from VBA into c# VSTO:
M_Script = LoadTextFile(qname, wk)
qSource = workbook_path & "\" & qname & ".csv"
Dim qry As WorkbookQuery
Set qry = wk.Queries.Item(qname)
qry.Formula = M_Script
Set qry = wk.Queries.Add(qname, M_Script, qSource)
wk.Connections.Add2 "Query - " & query.Name, _
"Connection to the '" & query.Name & "' query in the workbook.", _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _
, """" & query.Name & """", 6, True, False
Is there an easy equivalent? I could not find the wk.Queries. I don't want the data to be loaded into the worksheet but create only a connection to the query.
Thanks in advance!
回答1:
I ended up using the following approach. Though it's not really c# and I hope I will find a better solution at some point. VSTO Documentation is really sub-standard.
public void addQuery(string m_script_path, string query_name, Excel.Workbook wk)
{
VBComponent newStandardModule;
if(wk.VBProject.VBComponents.Count==0){
newStandardModule = wk.VBProject.VBComponents.Add(Microsoft.Vbe.Interop.vbext_ComponentType.vbext_ct_StdModule);
}
else
{
newStandardModule = wk.VBProject.VBComponents.Item(1);
}
var codeModule = newStandardModule.CodeModule;
// add vba code to module
var lineNum = codeModule.CountOfLines + 1;
var macroName = "addQuery";
var codeText = "Public Sub " + macroName + "()" + "\r\n";
codeText += "M_Script = CreateObject(\"Scripting.FileSystemObject\").OpenTextFile(\""+m_script_path+"\", 1).ReadAll" + "\r\n";
codeText += "ActiveWorkbook.Queries.Add Name:=\""+ query_name+"\", Formula:=M_Script\r\n";
codeText += "ActiveWorkbook.Connections.Add2 _\r\n";
codeText += "\"Query - test\", _\r\n";
codeText += "\"Connection to the '" + query_name + "' query in the workbook.\", _\r\n";
codeText += "\"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" + query_name + ";Extended Properties=\" _\r\n";
codeText += ", \"\"\"" + query_name + "\"\"\", 6, True, False\r\n";
codeText += "End Sub";
codeModule.InsertLines(lineNum, codeText);
var macro = string.Format("{0}.{1}", newStandardModule.Name, macroName);
wk.Application.Run(macro);
codeModule.DeleteLines(lineNum, 9);
}
来源:https://stackoverflow.com/questions/61622872/adding-power-queries-to-excel-using-c-sharp