Export SQL query results into a multi tabbed Excel spreadsheet - excel

I want to write a set of 100 select queries in DB2 10.1 to return all rows in each table in the database and have the results exported to an excel spreadsheet with a new tab for each result set.
Is this possible and if so how can I do it?
At the moment the only way I can do this looks like to export each result set and then manually create the multi tabbed spreadsheet by copying each tab across.
Thanks

You can use EasyXLS API for Excel with scripting languages like VB Script.
The VBS code should be similar with this one:
'The class that exports result set to Excel file
Set xls = CreateObject("EasyXLS.ExcelDocument")
' The class used to format the cells
Dim xlsAutoFormat
set xlsAutoFormat = CreateObject("EasyXLS.ExcelAutoFormat")
xlsAutoFormat.InitAs(AUTOFORMAT_EASYXLS1)
For query = 1 To 100
' Add a new sheet
xls.easy_addWorksheet_2("Sheet" & query)
set xlsSheet = xls.easy_getSheetAt(query - 1)
' Create the record set object
Dim objResultSet
Set objResultSet = CreateObject("ADODB.Recordset")
objResultSet.Open queryString, objDBConnection
' Create the list that will store the values of the result set
Dim lstRows
Set lstRows = CreateObject("EasyXLS.Util.List")
' Add the header to the list
Dim lstHeaderRow
Set lstHeaderRow = CreateObject("EasyXLS.Util.List")
lstHeaderRow.addElement("Column 1")
lstHeaderRow.addElement("Column 2")
lstHeaderRow.addElement("Column 3")
lstRows.addElement(lstHeaderRow)
' Add the values from the database to the list
Do Until objResultSet.EOF = True
set RowList = CreateObject("EasyXLS.Util.List")
RowList.addElement("" & objResultSet("Column 1"))
RowList.addElement("" & objResultSet("Column 2"))
RowList.addElement("" & objResultSet("Column 3"))
lstRows.addElement(RowList)
' Move to the next record
objResultSet.MoveNext
Loop
xlsSheet.easy_insertList_2 lstRows, xlsAutoFormat
Next
' Export result sets to Excel file
xls.easy_WriteXLSFile("c:\Result sets.xls")
Check also this link about exporting lists of data to Excel.
If you will choose a non scripting language, the API has methods that insert data directly from the result set and the lists can be skiped. Check another sample here.

Related

how to import excel to datagrid, then filter by db values

my question about import excel to datagridview but there is an extra case.
I have also a oledb database with store code and store names.
I want it to show only store codes from db that are in the database after imported.
my codes here;
Dim conn As OleDbConnection
Dim dtr As OleDbDataReader
Dim dta As OleDbDataAdapter
Dim cmd As OleDbCommand
Dim dts As DataSet
Dim excel As String
Dim OpenFileDialog As New OpenFileDialog
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
OpenFileDialog1.Filter = "All Files (*.*)|*.*|Excel files (*.xlsx)|*.xlsx|CSV Files (*.csv)|*.csv|XLS Files (*.xls)|*xls"
If (OpenFileDialog1.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
DataGridView1.Columns.Clear()
Dim fi As New FileInfo(OpenFileDialog1.FileName)
Dim FileName As String = OpenFileDialog1.FileName
excel = fi.FullName
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel + ";Extended Properties=Excel 12.0;")
dta = New OleDbDataAdapter("Select * From [Sheet1$]", conn)
dts = New DataSet
dta.Fill(dts, "[Sheet1$]")
DataGridView1.DataSource = dts
DataGridView1.DataMember = "[Sheet1$]"
conn.Close()
End If
firstly sorry for my terrible english :)
images as follows;
Main Form
Store List Form
I want only the ones in the store list to be displayed in datagrid.. :\
It's not exactly clear what your current presentation/display looks like, what the problem is, and what your desired presentation/display should look like. But you have asked about selecting only one part of the data you are importing, which is presumably found in only one column of the imported Excel data.
When the datatable is created, it has the columns and rows from the Excel worksheet. The columns will be data from the first row, and the rows will be the records from the succeeding rows in the worksheet. You can access both the header data and the row data easily. The code below is VERY rough but for you to see how to gain access to the data in the datatable which you have already very successfully imported in the limited code shown above.
Dim columns = datatable.Columns
Dim rows = datatable.Rows
Dim columns1 = columns(0)
Dim rows1 = rows(0)
Dim element1 = rows1(0)
Columns will have all the headers, so you can locate the column with the store codes or store names. Then the rows will have the data for each store. So above, rows1 is the first row of data and element1 is the data in that row from columns1, and so on. The (0) is the index into the respective collections.
You will, of course, have to write code to extract the data you want and if necessary eliminate duplicates, but the data is all there already.
Hopefully getting the data into a list and then sorting, filtering and selecting the data should be relatively straightforward, but if not, add a comment. That's kind of a different problem. You asked about getting only the store codes.
Added: Based on your additional images and explanation, you are looking to perform an SQL INNER JOIN operation. From the w3schools.com page on SQL INNER JOIN, "The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns." This is something you will have to study and learn, but it should provide what you need in this case. You will need to define and construct both tables and then perform the JOIN.
And, by the way, you could also follow the link provided in the first comment by T.S., and if that solves your problem, it's a far simpler solution.

SAPgui script with variables values from Excel

I need to populate dates on fields in SAP which if manually entered is properly captured by the script recorder.
Is it possible to update the script dates using a cell link in Excel?
session.findById("wnd[0]/usr/ctxtLKO74-PERIO").Text = "2"
session.findById("wnd[0]/usr/ctxtLKO74-BUPERIO").Text = "2"
session.findById("wnd[0]/usr/txtLKO74-GJAHR").Text = "2016"
session.findById("wnd[0]/usr/ctxtLKO74-BZDAT").Text = "29.02.2016"
I plan to copy the recorded SAP script and incorporate it in an Excel macro as a button.
You may try like this:
Set app = CreateObject("Excel.Application")
Set wbook = app.Workbooks.Open("c:\tmp\prices.xls")
set sheet = wbook.Sheets("Tabelle1")
session.findById("wnd[0]/usr/ctxtLKO74-PERIO").Text = sheet.Cells(1,2).Value
session.findById("wnd[0]/usr/ctxtLKO74-BUPERIO").Text = sheet.Cells(1,3).Value
session.findById("wnd[0]/usr/txtLKO74-GJAHR").Text = sheet.Cells(1,4).Value
session.findById("wnd[0]/usr/ctxtLKO74-BZDAT").Text = sheet.Cells(1,5).Value
Get App object, then get workbook and worksheet objects, and then assign your script cell values.
Everything is well discussed here including all the comments asking for different scenarios. https://scn.sap.com/thread/1699675

Using VBA to get data from SAS and limit the data set

I need to import data from SAS to excel via VBA. The import needs to run eg. on workbookOpen or Worksheet_BeforeDoubleClick or it can be called in any macro. This is solved in the below code:
Sub GetSASdata()
Dim obConnection As ADODB.Connection
Dim obRecordset As ADODB.Recordset
Dim i As Integer
Set obConnection = New ADODB.Connection
' Do not get stuck on the choice of connection provider.
obConnection.Provider = "sas.LocalProvider"
obConnection.Properties("Data Source") = "C:\path\"
obConnection.Open
Set obRecordset = New ADODB.Recordset
obRecordset.Open "MySAStable", obConnection, adOpenDynamic, adLockReadOnly, ADODB.adCmdTableDirect
'add header row
Cells(1, 1).Select
For i = 0 To obRecordset.Fields.Count - 1
ActiveCell.Offset(0, i).Value = obRecordset.Fields(i).Name
Next i
obRecordset.MoveFirst
obRecordset.Filter = "Weight > 0"
Cells(2, 1).Select
ActiveCell.CopyFromRecordset obRecordset, 100
obRecordset.Close
Set obRecordset = Nothing
obConnection.Close
Set obConnection = Nothing
End Sub
In this example I have restricted the output to be only the first 100 rows. However, the original data set is 1.4 m rows and 150 columns, and I want to be able to restrict the data import to only take columns that I define and rows which meet certain criteria. In sql terms:
select col1, col2, col10, col11 from MySAStable where code = MyCode and Date > MyDate
But I cannot find a way to do it. The first criteria is that the code should run entirely from Excel.
I have experimented some with obRecordset.Filter but the performance is poor. It takes forever. So idealy I would like to import only the data that I need. Is there a way to do this?
The
obConnection.Provider = "sas.LocalProvider"
is arbitrary. I found an example online, tested it and it worked. If someone has an answer to my problem that involves a different connection type, i am still interested to know. Very idealy the code can also be run by users who do not have SAS installed on their computer (but have access to the folder where data is placed.)
Thank you for any help
I have used two methods to read SAS data from within Excel.
The first uses SAS Add-In to MS Office. Do you have this product?
You can define the source with filters, and when the user opens the workbook, it will automatically refresh agains the datasource. You can also automate the refresh task with VBA code.
Secondly, I have done it with a Stored Process. If you have a stored process server, you can set up a web query in Excel and read the Stored Process that way, using any filter you need.

Use Excel spreadsheet from within Access

I have an Excel Spreadsheet that calculates a risk (of perioperative mortality after aneurysm repair) based on various test results.
The user inputs the test results into the spreadsheet (into cells) and then out comes a set of figures (about 6 results) for the various models that predict mortality. The spreadsheet acts as a complex function to produce the results one patient at a time.
I also have a (separate) access database holding data on multiple patients - including all the data on test results that go into the spreadsheet. At the moment I have to manually input this data into the spreadsheet, get the results out and then manually enter them onto the database.
Is there a way of doing this automatically. Ie can I export data1, data2, data3... from Access into the spreadsheet to the cells where the data needs to be input and then get the results (result1, result2, result3...) from the cells where the results are displayed ported back into access.
Ideally this could be done live.
I suppose I could try to program the functionality of the spreadheet into a complex function in access, but if I'm honest, I am not really sure how the algorithm in the spreadsheet works. It was designed by anaesthetists who are much cleverer than me....
Hope this makes sense. Any help much appreciated.
Chris Hammond
It's possible to automate Excel from Access.
Const cstrFile As String = "C:\SomeFolder\foo.xls"
Dim xlApp As Object
Dim xlWrkBk As Object
Dim xlWrkSt As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open cstrFile, ReadOnly:=True
Set xlWrkBk = xlApp.Workbooks(1)
Set xlWrkSt = xlWrkBk.Worksheets(1)
With xlWrkSt
.Range("A1") = 2
.Range("A2") = 19
Debug.Print .Range("A3")
End With
xlWrkBk.Close SaveChanges:=False
However, that seems like it would be cumbersome to repeat for each row of an Access table and I'm uncertain whether doing that live is reasonable.
I would try to adapt the Excel calculations to Access VBA functions and use those custom functions in an Access query. But I don't know how big of a task that would be. I suggest you shouldn't be scared off the the anaesthetists' cleverness; that doesn't mean they actually know much more about VBA than you. At least look to see whether you can tackle it.
To push the data back to Access, you can insert data from within the Excel VBA as follows:
dim val as variant
dim db as DAO.Database
val=thisworkbook.range("a1").value
set db=OpenDatabase("c:\myAccessDB.accdb")
db.execute "insert into patientData (someField) values (" & val & ")",dbFailOnError
db.Close
You'll need to add a reference to the Microsoft Office Access Database Engine Object Library.
Not sure to perfectly understand what you want, but if you just want to export the results of a query to a spreadsheet, you could use the following:
Private Sub ExportAccessDataToExcel()
Dim SqlString As String
SqlString = "CREATE TABLE testMeasurements (TestName TEXT, Status TEXT)"
DoCmd.RunSQL (SqlString)
SqlString = "INSERT INTO testMeasurements VALUES('Average Power','PASS')"
DoCmd.RunSQL (SqlString)
SqlString = "INSERT INTO testMeasurements VALUES('Power Vs Time','FAIL')"
DoCmd.RunSQL (SqlString)
SqlString = "SELECT testMeasurements.TestName, testMeasurements.Status INTO exportToExcel "
SqlString = SqlString & "FROM testMeasurements "
SqlString = SqlString & "WHERE (((testMeasurements.TestName)='Average Power'));"
DoCmd.RunSQL (SqlString)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel7, "exportToExcel", "C:\TestMeasurements.xls", True, "A1:G12"
End Sub
Source: http://www.ehow.com/how_7326712_save-access-query-excel-vba.html
This could be done either directly from the database or from Excel (you would need to open the database with Excel VBA to do so, but most of the Office Suite products interact well with each other).
If you want to push the data of your spreadsheet into an Access database, that's different. You just have to open the database and loop through INSERT query. Here is a quick example, you just need to add the loop:
Dim db as DAO.Database
Set db = OpenDatabase(myDataBase.mdb)
Call db.Execute("INSERT INTO myTable (Field1, Field2) VALUES('Value1', 'Value2')")

Filling BAPI import table parameter in EXCEL using VBA

I have a query for me which requires to clear. I am using excel 2003. the sheet contains 12 columns. I need to do export data from excel to SAP. Before exporting I need to check if the record is exist or not, if exist then delete and insert.
I have two BAPIs for this one is import table, which needs to be filled the parameters, after filling this table the BAPI searches for the relevant records.
The list will be displayed in a table. I need to search that table with values from excel then import one field value to excel.
I write this code but, it is not working the BAPI giving Error 0.
Public Function Import_Order() As Boolean
Dim oBAPIGetOrder As Object
Dim oBAPIVariant1 As Object
Dim oBAPIVariant2 As Object
Dim oBAPIVariant3 As Object
Dim oBAPIImpOrder As Variant
Dim oBAPIRet As Boolean
Dim oDoNothing As Variant
gBAPIPlanOrder = 0
Set oBAPIGetPlOrder = sBAPIControl.Add("PLANED_GET_DET_LIST") 'BAPI
Set oBAPIVariant1 = oBAPIGetPlOrder.exports.Item("SELECTIONCRITERIA") 'Internal table
Set oBAPIVariant2 = oBAPIGetPlOrder.Tables.Item("DETAILEDLIST") 'Table
oBAPIVariant1.Value("MATERIAL") = eMaterial
oBAPIVariant1.Value("PLANT") = ePlnPlant
lBAPIRet = oBAPIGetPlOrder.call
If lBAPIRet Then
'oBAPIImpOrder = oBAPIGetPlOrder.imports.Item("PLANNEDORDER_NUM")
a = oBAPIVariant2.Rows.Count
oBAPIImpOrder = oBAPIVariant2.Value("PLANNEDORDER_NUM")
Import_PlannedOrder = True
Else
oBAPIImpOrder = 0
Import_PlannedOrder = False
End If
End Function
Thanks in advance for any help...
please place the call function statement
lBAPIRet = oBAPIGetPlOrder.call
after directly the exports statement and before the tables and importstatements

Resources