how to extract the content of excel document with devexpress - excel

I would extract the content of excel document. It's possible with devexpress 13.2? Does anybody have any suggestion?
Thanks a lot in advance

Take a look at the DevExpress Spreadsheet Document Server (non-visual component with complete spreadsheet functionality available via its API). It allows developers to create, modify, save and print Excel documents, even when Microsoft Excel or Microsoft Office is not installed on the system. Supported File Formats - XLS, XLSX, XLSM, CSV and TXT;
Example: How to: Load a Document to a Workbook

I have done an import of an excel-file to update a SQL server table in the last days (with the DevExpress Grid only to show the imported data).
I my example, I:
ask the user for the filename (not necessary if you already know the
file name and path)
load the excel-file in a datatable (no devexpress needed for that)
show the datatable in a DevExpress Grid then
Note: in real live, I use the grid only to view/control the loaded data.
I then update an existing datatable on a SQL server from the loaded data in the datatable (code not included here).
Note: In the example, the sheet name always is "Sheet1" - maybe you want to make the sheet name also variable for your scenario...
Note: You don't need DevExpress, if you only want to import an Excel file into a DataTable (see ImportTable = ReadExcelIntoDataTable(cFileName, "Sheet1") and function ReadExcelIntoDataTable()) in code below.
' Chose the Excel-File over Open FileDialog()
' If you don't know the filename & path allready
Dim cFileName As String = ""
Dim filedialog As OpenFileDialog = New OpenFileDialog()
filedialog.Title = "Chose the File"
filedialog.DefaultExt = ".XLSX"
filedialog.ShowDialog()
cFileName = filedialog.FileName
'
If Not cFileName = "" Then
ImportTable = ReadExcelIntoDataTable(cFileName, "Sheet1")
If ImportTable.Rows.Count > 0 Then
Grid_Datenimport.DataSource = ImportTable
' Do some format (if you like)..
GridView2.Columns("ColumnX").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
GridView2.Columns("ColumnX").DisplayFormat.FormatString = "dd/MM/yyyy HH:mm:ss"
GridView2.Columns("ColumnX").Width = 160
End If
End If
Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable
Dim RetVal As New DataTable
Dim strConnString As String
strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";"
Dim strSQL As String
strSQL = "SELECT * FROM [" & SheetName & "$]"
Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString)
y.Fill(RetVal)
Return RetVal
End Function

Related

Link Table between MS Access files from MS Excel

How can I create a Table link within a MS Access *.accdb file, linking to another table in an MS Access *.accdb file, but from VBA code within an MS Excel *.xlsx file.
Database1 in file1
Database2 in file2
Excel VBA Code in file3
Execute code in file3 to link a table of file2 to file1, so that it appears as linked table within file1.
Details:
I have a complex script creating a large table and join mappings based on a MS Excel Design, since it is more user friendly to design the things in an MS Excel Table. Everything works great so far, but I need the last step, LINK the original table.
Within MS Access I would do
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:=SRC_FILE_PATH, _
ObjectType:=acTable, _
Source:=SRC_TABLE_NAME, _
Destination:=DESTINATION_TABLE_NAME
But since I am executing VBA Code within Excel, only using the connection to the database via a DAO.Database object, this command doesn't work.
Using the DAO reference library in Excel
Dim wrkDAOWorkspace As DAO.Workspace
Dim dbsDAODatabase As DAO.Database
Dim tdfNewLinkedTable As DAO.TableDef
Set wrkDAOWorkspace = CreateWorkspace("WorkspaceForLinkCreation", "Admin", "", dbUseJet)
Set dbsDAODatabase = wrkDAOWorkspace.OpenDatabase("c:\file1.accdb")
Set tdfNewLinkedTable = New DAO.TableDef
With tdfNewLinkedTable
.Name = "TestTableLinked"
.Connect = ";DATABASE=c:\file2.accdb"
.SourceTableName = "TestTableLinkTo"
End With
dbsDAODatabase.TableDefs.Append tdfNewLinkedTable
Something like this should do it for you. Modify to suit your needs...
Private Sub Command1_Click()
DoCmd.SetWarnings False
Dim InputFile As String
Dim InputPath As String
InputPath = "C:\your_path_here\"
InputFile = Dir(InputPath & "*.xls")
Do While InputFile <> ""
DoCmd.TransferSpreadsheet acImport, , InputFile, InputPath & InputFile, True '< The true is for column headers
InputFile = Dir
Loop
End Sub

VB6 To Xls without Excel

I have to transfer data from several Flexgrids in different Forms in a VB6 application to .xls files in computers which do not have excel installed. Openoffice, LibreOffice, etc are installed in these PCs.
I developed a common procedure which takes a FlexGrid as a parameter and transfers its data to xls. This procedure uses DAO. As various columns in various FlexGrids contain various data types, in the procedure I am defining the fields as type "dbText".
t.Fields.Append t.CreateField(pFlxGrd.TextMatrix(0, j), dbText)
Transfer from any grid to xls is working fine. But, a problem is, for every cell that contains data, single quotes are inserted to indicate its data of Text type.
Is there any way to remove or avoid these quotes? As numeric data are to be used for summations, etc, these quotes have to be gotten rid of.
You can do this with either the Jet engine, ODBC or accdb. If you are on a 64 bit system, make sure you run it from the 32-bit cmd prompt in windows\syswow64\cmd. I don't have VB6 installed so this solution has only been tested in vbscript, which is very similar. You just have to add the types to the dim statement.
dim connExcel, connExcelStr, rsExcel, xlpath
' Get the parameter from the command line
xlpath = WScript.Arguments.Item(0)
' Create the connection
set connExcel = CreateObject("ADODB.Connection")
' Setup the connection string
' xlpath = "U:\JetExcel\data.xls"
connExcelStr = "Driver={Microsoft Excel Driver (*.xls)};"
connExcelStr = connExcelStr & "Dbq=" & xlpath & ";"
connExcelStr = connExcelStr & "FIRSTROWHASNAMES=1;"
connExcelStr = connExcelStr & "READONLY=FALSE;"
connExcelStr = connExcelStr & "CREATE_DB=""" & xlpath & """;"
' Create a workbook
WScript.echo connExcelStr
connExcel.Open connExcelStr
' Create a worksheet
sqlQuery = "create table [Sheet1] (ID Number, FirstName Text, LastName Text)"
WScript.echo sqlQuery
set rsExcel = connExcel.Execute(sqlQuery)
' Put data into the worksheet
sqlQuery = "insert into [Sheet1] (ID, FirstName, LastName) values"
sqlQuery = sqlQuery & "(1, 'Humpty', 'Dumpty')"
WScript.echo sqlQuery
set rsExcel = connExcel.Execute(sqlQuery)
' Close workbook
connExcel.Close
set connExcel = nothing
If the script is named xxx.vbs, to create an excel sheet
cscript xxx.vbs test.xls
There is a much faster solution to copy the data from a flexgrid (without the quotation marks) shown in vbForums from a while back - The advantage of this methods is that they work pretty fast, compared to send/bring data cell by cell
Private Sub FlexToExcel()
Dim xlObject As Excel.Application
Dim xlWB As Excel.Workbook
Set xlObject = New Excel.Application
'This Adds a new woorkbook, you could open the workbook from file also
Set xlWB = xlObject.Workbooks.Add
Clipboard.Clear 'Clear the Clipboard
With MSFlexGrid1
'Select Full Contents (You could also select partial content)
.Col = 0 'From first column
.Row = 0 'From first Row (header)
.ColSel = .Cols - 1 'Select all columns
.RowSel = .Rows - 1 'Select all rows
Clipboard.SetText .Clip 'Send to Clipboard
End With
With xlObject.ActiveWorkbook.ActiveSheet
.Range("A1").Select 'Select Cell A1 (will paste from here, to different cells)
.Paste 'Paste clipboard contents
End With
' This makes Excel visible
xlObject.Visible = True
End Sub
See THIS link for more information.

Creating Dynamic Excel Connection in SSIS

When I use a static ole db > excel connection manager in SSIS I set the file I want to connect to in the excel connection manager, create the data flow excel destination, hook it up to ole db source and map the fields.
In this case I want to do the same but instead of linking to an existing file I want to create a new file and put my data there. Now I know I can do a SQL task and create a new table (sheet effectively) in an existing excel connection but in this case I have made a script task to create the full path where my new file will go e.g. c:\docs\mypjt\fileformarch.xls with this code:
Public Sub Main()
'
' Add your code here
'
Dim strFileName As String
Dim strFolderName As String
Dim strMonthNameShort As String
Dim strFullPath As String
Dim lastMonth As New Date(DateTime.Today.Year, DateTime.Today.Month - 1, 1)
strFileName = Dts.Variables("FileName").Value.ToString
strFolderName = Dts.Variables("FolderName").Value.ToString
strMonthNameShort = MonthName(lastMonth.Month, True)
strFullPath = strFolderName & strFileName.Substring(0, strFileName.IndexOf(".xls")) & strMonthNameShort & ".xls"
Dts.Variables("FullPath").Value = strFullPath
Dts.TaskResult = Dts.Results.Success
End Sub
But I don't understand how to create my dynamic connection and mappings, I tried mucking about with connection strings in my excel connection manager etc to no avial so figure I am not getting the full picture of exactly what I need to do.
Not sure if I need a template with the column headings to set up a default mapping, but then I have read many cases where the excel connection manager only requires an initial connection to "a" file then the dynamic connectionstring proerty takes over when you run it, but then how does it know what the mappings are if you are creating a new file?
I am grateful for any advice you can give.
Thanks
Andrew

Select all Sheet from an Excel File

basically, i am uplaoding a dynamic excel file and i want to select all the sheets containing a data and have it in a dataset. But i dont know how, all I can get is from a static sheet name and only one sheet per select, how can i select all shhet within one excel file and have it in a dataset? thanks.
this is what i got so far
Dim exConS As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
excelfile & ";Extended Properties=Excel 8.0;"
Dim exCon As New OleDbConnection(exConS)
Dim dsExcel As New DataSet()
Dim sExcel As String = "SELECT * FROM [SSI-data3$]"
Dim daExcel As New OleDbDataAdapter(sExcel, exCon)
daExcel.Fill(dsExcel)
I think you can use GetSchema with suitable schema name from the Jet schema set to retrieve the names of tables - in Excel, this includes both named ranges and sheets.
You would have to create a UNION query to get every sheet in the one set of data, which would only be suitable if the columns matched.
I think you should use Microsoft.Office.Interop.Excel to get worksheet names and then with a foreach you can get them

Performance in reading Excel File using OpenXML

As of now im reading all version of excel files using oledbreader. i referred a dll for reading Excel 2010 files. but i cannot read some excel 2010 files using oledbreader. so i would like to use openxml for reading all excel files. is ter any performance issue in this?
which is better?
I have had very good luck using the following code to retrieve table names(worksheet names) and column names from Excel spreadsheets.
Private Sub GetWorksheetData
Dim xlBaseConnStr1 As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=XLS;Extended Properties=""Excel 8.0;HDR=Yes"""
Dim xlBaseConnStr2 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=XLS;Extended Properties=""Excel 12.0 Xml;HDR=YES"""
Dim xlName As String
Dim conStr As String
Dim oDia As New OpenFileDialog
oDia.ShowDialog()
xlName = oDia.FileName
If xlName = "" Then
Exit Sub
End If
Dim extType As String = Path.GetExtension(xlName)
Select Case extType
Case ".xls"
conStr = xlBaseConnStr1.Replace("XLS", xlName)
Case ".xlsx"
conStr = xlBaseConnStr2.Replace("XLS", xlName)
Case Else
MessageBox.Show("Unrecognized file type")
Exit Sub
End Select
Dim dtSheets As New DataTable
Using cn As New OleDbConnection(conStr)
cn.Open()
dtSheets = cn.GetSchema("Columns")
End Using
DataGrid1.ItemsSource = dtSheets.DefaultView
End Sub
The above chunk of code returns the following data from a random Excel spreadsheet that I had laying around.
You will need to import the following namespaces for this to work:
Imports System.Data.OleDb
Imports System.Data
Imports Microsoft.Win32
Imports System.IO
If the spreadsheet that you are trying to access has macros, the above code may fail.

Resources