How to copy workbook (.aspx file) from html link to current workbook - asp.net

I have trouble with the following tasks in excel VBA:
At my work, we use a document management platform called TeamShare: [https://www.lector.dk/en/products/]
I want to create a code in VBA, that loops over a range of links to this document management platform in my workbook, ie. loops over other workbooks, opens them and then copies a specified sheet to my current workbook.
I have tried putting together bits of codes from other sites, and the code works just fine when i run it in break mode. However, when I run the code all at once, the Excel program reopens, such that the current workbook cannot "communicate" with the opened workbook and I end up in an infinity loop (so no direct error message).
This is the code that only works in break mode:
Dim wbCopyTo As Workbook Dim wsCopyTo As Worksheet Dim i As Long Dim Count As Long Dim WBCount As Long Dim LastRow As Long Dim wb As Workbook Dim ws As Worksheet Dim URL As String Dim IE As Object Dim doc As Object Dim objElement As Object Dim objCollection As Object
Set wbCopyTo = ActiveWorkbook Set wsCopyTo = ActiveSheet
LastRow = wsCopyTo.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
The purpose of this piece of code is to get the DocID
A = InStr(wsCopyTo.Range("B" & i), "documentid=") + Len("documentid=")
B = InStrRev(wsCopyTo.Range("B" & i), "&")
DocID = Mid(wsCopyTo.Range("B" & i), A, B - A)
'Get URL
URL = wsCopyTo.Range("B" & i)
'Count number of open workbooks
WBCount = Workbooks.Count
With IE
New is the comman that opens excel sheet. This works as planned in breakmode, however the excel program reopens when i run the code all at once. I have tried other commandos here: "Workbooks.Open", I couldn't get this one to open the file and "Application.FollowHyperlink" only worked in break mode too, however, much much slower
.Navigate URL
'This was my solution to how to stop the rest of the code from executing until the new workbook has loaded.
Do Until Workbooks.Count = WBCount + 1: Loop
End With
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
'So in order to activate the workbook from the URL, I am looping over all my open workbooks and matching them on their unique Document ID. I found that the workbook from the URL wasn´t the "active workbook" per default.
For Each book In Workbooks If Mid(book.Name, 12, Len(DocID)) = DocID Then
book.Activate
Set wb = ActiveWorkbook
Set ws = ActiveSheet
End If
Next book
Here i copy the desired sheet to my initial workbook
wb.Worksheets("SpecificSheetIWantToCopy").Copy After:=wbCopyTo.Worksheets("Sheet1") wbCopyTo.Sheets(ActiveSheet.Name).Name = DocID
Next i
End Sub
I am using excel 2010.
I hope you can help me resolve this problem. Please ask if you need any more information, that i haven´t provided.
Thanks in advance.

Related

Open XML SDK Open and Save not working

I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)

How to test whether an uploaded Excel file meets requirements

Background
Suppose I have a shiny app where the user can upload an Excel file. The users will have access to a certain Excel template and I want to make sure that only copies of this template are uploaded.
My current approach
My current approach is now as follows:
Check if sheet name xyz is present -> if not throw an error
Read data from sheet xyz, compare column names with requirements -> if missing columns throw an error
Repeat for all necessary sheets
Problem with the current approach
This requires a lot of hard coding required sheet names and required column names and becomes tedious.
Question
So my question: how can I assure that the user provides a valid file? What strategies do you usually use to make sure that the uploaded file can be properly processed by your apps?
Pseudo Code
library(shiny)
library(tidyverse)
ui <- fluidPage(fileInput("file", "Upload Excel"))
server <- function(input, output, session) {
observe({
req(input$file)
sheet1 <- tryCatch(read_xlsx(input$file$datapath, sheet = "xyz"),
error = function(e) {
## do some sort of error handling, e.g. write to a reactiveValue list
})
if (!all(.REQUIRED_FIELDS_FOR_XYZ %in% names(sheet1))) {
## signal error
}
})
}
If you are already using Excel, why not use a Macro to do the work for you. Consider listing file paths, checking format types, cell addresses, cell values, etc. The Macro below will do most of the heavy lifting for you.
Sub GetFolder_Data_Collection()
Dim colFiles As Collection, c As Range
Dim strPath As String, f, sht As Worksheet
Dim wbSrc As Workbook, wsSrc As Worksheet
Dim rw As Range
Dim sh As Worksheet, flg As Boolean
Set sht = ActiveSheet
strPath = ThisWorkbook.Path
Set colFiles = GetFileMatches(strPath, "*.xlsx", True)
With sht
.Range("A:I").ClearContents
.Range("A1").Resize(1, 5).Value = Array("Name", "Path", "Cell", "Value", "Numberformat")
Set rw = .Rows(2)
End With
For Each f In colFiles
Set wbSrc = Workbooks.Open(f)
Set wsSrc = wbSrc.Sheets(1)
For Each c In wsSrc.Range(wsSrc.Range("A1"), _
wsSrc.Cells(1, Columns.Count).End(xlToLeft)).Cells
rw.Cells(2).Value = wbSrc.Path
sht.Hyperlinks.Add Anchor:=rw.Cells(1), Address:=wbSrc.Path, TextToDisplay:=wbSrc.Name
rw.Cells(3).Value = c.Address(False, False)
rw.Cells(4).Value = c.Value
rw.Cells(5).Value = c.NumberFormat
i = 6
For Each sh In Worksheets
If sh.Name Like "Sheet1*" Or sh.Name Like "*Sheet2*" Then rw.Cells(i).Value = sh.Name & " Exists"
i = i + 1
Next
Set rw = rw.Offset(1, 0)
Next c
wbSrc.Close False
Next f
End Sub
'Return a collection of file objects given a starting folder and a file pattern
' e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetFileMatches(startFolder As String, filePattern As String, _
Optional subFolders As Boolean = True) As Collection
Dim fso, fldr, f, subFldr
Dim colFiles As New Collection
Dim colSub As New Collection
Set fso = CreateObject("scripting.filesystemobject")
colSub.Add startFolder
Do While colSub.Count > 0
Set fldr = fso.GetFolder(colSub(1))
colSub.Remove 1
For Each f In fldr.Files
If UCase(f.Name) Like UCase(filePattern) Then colFiles.Add f
Next f
If subFolders Then
For Each subFldr In fldr.subFolders
colSub.Add subFldr.Path
Next subFldr
End If
Loop
Set GetFileMatches = colFiles
End Function
PUT THIS CODE IN AN XLSB OR XLSM EXCEL FILE IN THE SAME FOLDER AS YOUR EXCEL FILES.
It's probably just easier to do this kind of thing with Excel, and I'm a huge proponent of using the right tool for the job.

Exporting data from PowerPivot

I have an enormous PowerPivot table (839,726 rows), and it is simply too big to copy-paste into a regular spread sheet. I have tried copying it and then reading it directly into R using the line data = read.table("clipboard", header = T), but neither of these approaches work. I am wondering if there is some add-on or method I can use to export my PowerPivot table as a CSV or .xlsx? Thanks very much
Select all the PowerPivot table
Copy the data
Past the data in a text file (for example PPtoR.txt)
Read the text file in R using tab delimiter: read.table("PPtoR.txt", sep="\t"...)
To get a PowerPivot table into Excel:
Create a pivot table based on your PowerPivot data.
Make sure that the pivot table you created has something in values area, but nothing in filters-, columns- or rows areas.
Go to Data > Connections.
Select your Data model and click Properties.
In Usage tab, OLAP Drill Through set the Maximum number of records to retrieve as high as you need (maximum is 9999999 records).
Double-click the measures area in pivot table to drill-through.
another solution is
import the Powerpivot model to PowerBi desktop
export the results from PowerBI desktop using a Powershell script
here is an example
https://github.com/djouallah/PowerBI_Desktop_Export_CSV
A pure Excel / VBA solution is below. This is adapted from the code here to use FileSystemObject and write 1k rows at a time to the file. You'll need to add Microsoft ActiveX Data Objects Library and Microsoft Scripting Runtime as references.
Option Explicit
Public FSO As New FileSystemObject
Public Sub ExportToCsv()
Dim wbTarget As Workbook
Dim ws As Worksheet
Dim rs As Object
Dim sQuery As String
'Suppress alerts and screen updates
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
'Bind to active workbook
Set wbTarget = ActiveWorkbook
Err.Clear
On Error GoTo ErrHandler
'Make sure the model is loaded
wbTarget.Model.Initialize
'Send query to the model
sQuery = "EVALUATE <Query>"
Set rs = CreateObject("ADODB.Recordset")
rs.Open sQuery, wbTarget.Model.DataModelConnection.ModelConnection.ADOConnection
Dim CSVData As String
Call WriteRecordsetToCSV(rs, "<ExportPath>", True)
rs.Close
Set rs = Nothing
ExitPoint:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
Set rs = Nothing
Exit Sub
ErrHandler:
MsgBox "An error occured - " & Err.Description, vbOKOnly
Resume ExitPoint
End Sub
Public Sub WriteRecordsetToCSV(rsData As ADODB.Recordset, _
FileName As String, _
Optional ShowColumnNames As Boolean = True, _
Optional NULLStr As String = "")
'Function returns a string to be saved as .CSV file
'Option: save column titles
Dim TxtStr As TextStream
Dim K As Long, CSVData As String
'Open file
Set TxtStr = FSO.CreateTextFile(FileName, True, True)
If ShowColumnNames Then
For K = 0 To rsData.Fields.Count - 1
CSVData = CSVData & ",""" & rsData.Fields(K).Name & """"
Next K
CSVData = Mid(CSVData, 2) & vbNewLine
TxtStr.Write CSVData
End If
Do While rsData.EOF = False
CSVData = """" & rsData.GetString(adClipString, 1000, """,""", """" & vbNewLine & """", NULLStr)
CSVData = Left(CSVData, Len(CSVData) - Iif(rsData.EOF, 3, 2))
TxtStr.Write CSVData
Loop
TxtStr.Close
End Sub
Here is a lovely low-tech way:
https://www.sqlbi.com/articles/linkback-tables-in-powerpivot-for-excel-2013/
I think the process is a little different in Excel 2016. If you have Excel 2016, you just go to the data tab, go to Get External Data, and then Existing Connections (and look under Tables).
The other important thing is to click on Unlink (under Table Tools - Design - External Table Data). This unlinks it from the source data, so it really is just an export.
You can copy that data into another workbook should you wish to.
Data in Power Pivot is modeled, using DAX Studio to export data to csv or SQL.
after finished, you will see that Each model corresponds to a CSV file or SQL table.

Asp.net: Excel file uploading does not finish but gives no error message

I'm having a rather weird problem trying to upload an Excel file and storing it in a SQL server table in an ASP.net App.
The file is not too big: about 2.5 or 3 Mb.
The problem is that the upload gets "interrupted" after loading some rows, appearently without causing any specific error, since the load process finishes by showing a success message that I'm sending to the client:
"The process finished successfuly: XXX rows were uploaded from the
file".
The problem is that the XXX rows are not all the rows from the file. Depending on how much information there is in each column of the Excel file, the process is only uploading, for instance, 15500 rows from a total of 25000 that the file has. (If there's less information in the Excel file, it can upload, lets say 20000 of the 25000 rows that it may have)... the fact is that the file is not being "completely" uploaded.
I already tried increasing the "httprequest-maxRequestLength" value in the web.config, even though the file is not bigger than the default 4Mb file upload that ASP.net has.
The code (vb.net) that I'm using upload and read the file is, basically, this:
Dim connection As DbConnection = Nothing
Dim Command As DbCommand = Nothing
Dim ConexionStringExcel As String
Dim dr As DbDataReader
Dim mensajeError as String = ""
Dim ncAdic as Integer = 0
Dim nReg as Integer = 0
'String connection for Excel 2007: for now, I'm not allowing other Excel versions
ConexionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = " & sNombreArch & ";" & _
"Extended Properties=Excel 12.0 Xml;"
'sNombreArch is the full name of the uploaded file
connection = New OleDb.OleDbConnection(ConexionStringExcel)
Command = connection.CreateCommand()
Command.CommandText = "SELECT * FROM [" + nomHojaArch + "$]"
'---
'lblMensaje is a Label object in the aspx page:
'---
lblMensaje.Visible = False
Try
'Open the Excel file
connection.Open()
'Read file content
dr = Command.ExecuteReader()
While dr.Read
Try
'Two first columns of the file are mandatory in my case...
If Not IsDBNull(dr(0)) And Not IsDBNull(dr(1)) Then
'---
'dsTempCargue is a SqlDataSource object in the aspx page
'---
dsTempCargue.InsertParameters.Item("idReg").DefaultValue = dr(0)
dsTempCargue.InsertParameters.Item("nombre").DefaultValue = dr(1)
For ncAdic = 2 To 10
If Not IsDBNull(dr(ncAdic)) Then
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = dr(ncAdic)
Else
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = DBNull.ToString
End if
Next
dsTempCargue.Insert()
nReg = nReg + 1
Else
mensajeError = "Column A and B of the File cannot be empty"
Exit While
End If
Catch exRead As Exception
mensajeError = "Error reading the file or saving its content: " & exRead.Message
Exit While
End Try
End While
'If there was no error, show success message
If String.IsNullOrEmpty(mensajeError) Then
mensajeError = "The process finished successfuly. " & nReg.ToString() & " rows were uploaded from the file"
End IF
Catch ex As Exception
mensajeError = "Error uploading the file: " & ex.Message
End Try
lblMensaje.Text = mensajeError
lblMensaje.Visible = True
Why do you think this uploading process is failing to read the entire file???... Any advice will be appreciated.
Thanks a lot,
Diego
For the tables that you are storing the rows in, what datatype are the various columns? Perhaps the content of one of the cells is incompatible with the column datatype. Do you have any way of checking?
Even though I'm really not sure about what could have been the cause of the error, I finally managed to get it working by changing my code to use a Third-party library that I found and that had some good comments, which is available here:
http://exceldatareader.codeplex.com/
I'm not really sure about what the original problem was and why using this library solved the issue, but It worked. (Perhaps when I have some time I'll try to find more info about this problem I had)
Thanks Patrick for your comments and all for the interest

save excel using EPPlus

could someone help me with this error??
I tried to save excel file using EPPlus
[IOException: The process cannot access the file 'C:\Users\Julian\Downloads\EmployeeMaster.xls' because it is being used by another process.]
here is my code :
Dim conn As New ConnectionVB
Dim newfile As FileInfo = NewFileInfo("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Using p As ExcelPackage = New ExcelPackage(newfile)
SetWorkBookProperties(p)
conn.connect()
Dim ws As ExcelWorksheet = CreateSheet(p, "EmnployeeMaster")
Dim dt As New DataTable
Dim connString As String
connString = "Select * from EmployeeMaster"
dt = conn.openDataTable(connString)
Dim rowIndex As Integer
rowIndex = 2
CreateHeader(ws, rowIndex, dt)
CreateData(ws, rowIndex, dt)
Dim bin As Byte()
bin = p.GetAsByteArray()
Dim path As String
path = "C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls"
File.Delete("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Dim stream As Stream = File.Create(path)
File.WriteAllBytes(path, bin) <- I got the error here
Start(path)
stream.Close()
End Using
Appriciate all help/advice with this error
Regards Siekh
As from your Error shows: EmployeeMaster.xls file is being used by another process.
Your code DryRun:
In your EmployeeMaster.xls file you make another new sheet name as EmnployeeMaster and then you create Header, and Data in this sheet.
problem arise when you write to file. you have to just save WorkSheet by doing .
because just open your .xls file with the help of EPPlusPackage and then by code Add your custom sheet in .xls file and just save.
p.Save(); // you need to save this temporary sheet.
Problems may be:
EPPLUS cannot open xls files, only xlsx files.
Why you delete File.
solution: you can rename and then move.
EPPlus hold your file when you instantiate object for ExcelPackage(with the same Path)
Two Problems:
EPPlus does not support xls files.
For debugging why the file is used, I recommend using SysInternal's "process explorer", you can find it here.

Resources