I am trying to open a excel file in vb.net with excel interop
then add a formula to F2 then save as excel as csv
Can someone point me how to concatenate an ' with number in a formula cs when i write ' the Visual studio consider it as a comment not a formula
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim newFileName As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".csv"
Dim oExcelFile As Object
Try
oExcelFile = GetObject("c:\database", "Excel.Application")
Catch
oExcelFile = CreateObject("Excel.Application")
End Try
oExcelFile.Visible = True
Dim strfilename As String = "Libanpost" + Date.Today.ToString("ddMMyyyy") + ".xls"
Dim strFolderPath As String = "c:\database"
oExcelFile.Workbooks.Open(strFolderPath + "\" + strfilename)
Dim oExcelsheet As Excel.Worksheet
oExcelsheet = oExcelFile.sheets("table1")
oExcelsheet.Range("f1").Value = "CRC"
oExcelsheet.Range("f2").Formula = " = IF(LEN(A2)=2,(CONCATENATE("'00000",A2)),IF(LEN(A2)=3,CONCATENATE("'0000",A2),IF(LEN(A2)=4,CONCATENATE("'000",A2),IF(LEN(A2)=5,CONCATENATE("'00",A2),IF(LEN(A2)=6,CONCATENATE("'0",A2),A2)))))"
oExcelFile.DisplayAlerts = False
oExcelFile.ActiveWorkbook.SaveAs(Filename:=strFolderPath + "\" + newFileName, FileFormat:=Excel.XlFileFormat.xlCSV, CreateBackup:=False)
oExcelFile.ActiveWorkbook.Close(SaveChanges:=False)
Dim file_count As Integer = File.ReadAllLines(strFolderPath + "\" + newFileName).Length
MsgBox(file_count)
oExcelFile.DisplayAlerts = True
oExcelFile.Quit()
oExcelFile = Nothing
The problem is that you have included double quotes (") inside your string literal. The first double quote inside the string is taken to mean the end of the string. It happens to be followed by a single quote which indicate the start of a comment. If you include a double quote inside a string literal, you need to have two of them. Here is the corrected statement (I split it over three lines for readability).
oExcelsheet.Range("f2").Formula = "=IF(LEN(A2)=2,(CONCATENATE(""'00000"",A2))," _
& "IF(LEN(A2)=3,CONCATENATE(""'0000"",A2),IF(LEN(A2)=4,CONCATENATE(""'000"",A2)," _
& "IF(LEN(A2)=5,CONCATENATE(""'00"",A2),IF(LEN(A2)=6,CONCATENATE(""'0"",A2),A2)))))"
Related
Its a c# code written in a SSIS script task component.
PS_script + #"""$compname = " "\" + Row.computername"\" +
"$appname =" + Row.applicationname + " $appvalue = " + Row.appvalue +
"";
I am tying the MS deploy and setting params coming from table driven. The above statement throws error as I am not able to pass double quotes in computername param.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
In C#, a literal string with the prefix #, "" will be replaced by ".
Example :
var str = #"$compname = """ + Row.computername + #"""";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
You can also escape a character with \. Then \" will be replaced by ".
Example :
var str = "$compname = \"" + Row.computername + "\"";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
In you case, you can also use string.Format to more lisibility :
string.Format(
#" $compname = ""{0}"" $appname = ""{1}"" $appvalue = ""{2}""",
Row.computername, Row.applicationname, Row.appvalue
);
Warning, with SSIS script task, you can't use string interpolation (the literal string prefix $).
I am new to this forum and hoping to get some help.
I have a an HTML string having text and several base64 images.
I need to loop through all image tags adding a slash / before
the closing tag > so that each image ends with /> and return
a new html string with the changes.
so each
<IMG src="data:image/png;base64,iVBORw0KG....">
should then be
<IMG src="data:image/png;base64,iVBORw0KG...."/>
I am not versed with html and I am wondering how to do it
(using regex?).
Here is some pseudo code:
Function GetSourceImges(Sourcehtml As String) As List(Of String)
Dim listOfImgs As New List(Of String)()
'use regex to find image tags
'Return list of base64 image tags
End Function
For each image in list
insert a slash appropriately
next
Reconstitute a new html string with edited images
Thanks
Map all "IMG" tags using LINQ and use their indexes as an anchor to fix the missing "/" characters. please see my comments inside the code.
Sub Main()
Dim htmlstring As String = "<IMG src=""data:image/png;base64,iVBORw0KG....""> " & vbCrLf _
& "<img src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>" & vbCrLf _
& "<IMG src=""data:image/png;base64,iVBORw0KG...."">" & vbCrLf _
& "<p>blahblah</p>"
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(htmlstring, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < htmlstring.Length - 1
If htmlstring(counter) = ">" Then
If htmlstring(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
htmlstring = htmlstring.Insert(counter, "/")
End If
Exit While
End If
counter += 1
End While
Next
Console.WriteLine(htmlstring)
Console.ReadLine()
End Sub
Surprisingly it works with the console app but doesn't when I view it on a richtextbox as in btnEditHTML method below. The generated pdf has only one red dot and not two.
Can't say why.
I must say you have been very helpfull.
'SetTable and customimagetagprocessor borrowed from [here] iTextsharp base64 embedded image in header not parsing/showing
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.tool.xml
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml.parser
Imports iTextSharp.tool.xml.pipeline.css
Imports iTextSharp.tool.xml.pipeline.html
Imports iTextSharp.tool.xml.pipeline.end
Imports iTextSharp.tool.xml.html
Imports System.Text.RegularExpressions
Public Class Form1
Dim dsktop As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Public Function GetFormattedHTML(str As String) As String
'format images by changing > to />
' find all indxes of img using regex and lambda exprations '
Dim indexofIMG() As Integer = Regex.Matches(str.ToString, "IMG", RegexOptions.IgnoreCase) _
.Cast(Of Match)().Select(Function(x) x.Index).ToArray()
' check from each index of "IMG" if "/" is missing '
For Each itm As Integer In indexofIMG
Dim counter As Integer = itm
While counter < str.ToString.Length - 1
If str(counter) = ">" Then
If str(counter - 1) <> "/" Then
' fix the missing "/" using Insert() method '
str = str.ToString.Insert(counter, " /")
End If
Exit While
End If
counter += 1
End While
Next
Return str.ToString
End Function
Private Sub btnEditHTML_Click(sender As Object, e As EventArgs) Handles btnEditHTML.Click
Rtb.Text = String.Empty
'the 2 base64 images in the html below are actually just small red dots
Dim RawHTML As String = "<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">"
Rtb.Text = GetFormattedHTML(RawHTML)
'notice that the 2nd base64 string is not edited as required.
End Sub
Private Sub btnGenerate_Click(sender As Object, e As EventArgs) Handles btnGenerate.Click
'here I create a 2 column itextsharp table to parse my html into the cells
Dim doc As New iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 30)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New System.IO.FileStream(dsktop & "\testtable.pdf", System.IO.FileMode.Create))
doc.Open()
'set table columnwidths -------------------------------------------------------------
Dim MainTable As New PdfPTable(2) '2 column table
MainTable.WidthPercentage = 100
Dim Wth(1) As Single
Dim u As Integer = 2
For i As Integer = 0 To 1
Wth(i) = CInt(Math.Floor(2 * 500 / u))
Next
MainTable.SetWidths(Wth)
Dim htmlstr As String = GetFormattedHTML("<P>John Doe</P><IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==""> Jackson5<IMG " &
"src=""data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="">")
Dim Elmts = New ElementList()
Elmts = XMLWorkerHelper.ParseToElementList(htmlstr, Nothing)
Dim MinorTable As New PdfPTable(1)
MinorTable = SetTable(Elmts, htmlstr)
For i = 1 To 2
Dim Cell As New PdfPCell
Cell.AddElement(MinorTable)
MainTable.AddCell(Cell)
Next
doc.Add(MainTable)
doc.Close()
Process.Start(dsktop & "\testtable.pdf")
End Sub
Public Function SetTable(ByVal elements As ElementList, ByVal htmlcode As String) As PdfPTable
Dim tagProcessors As DefaultTagProcessorFactory = CType(Tags.GetHtmlTagProcessorFactory(), DefaultTagProcessorFactory)
tagProcessors.RemoveProcessor(HTML.Tag.IMG) ' remove the default processor
tagProcessors.AddProcessor(HTML.Tag.IMG, New CustomImageTagProcessor()) ' use our new processor
Dim cssResolver As ICSSResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(True)
cssResolver.AddCssFile(Application.StartupPath & "\pdf.css", True)
'see sample css file at https://learnwebcode.com/how-to-create-your-first-css-file/
'Setup Fonts
Dim xmlFontProvider As XMLWorkerFontProvider = New XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS)
xmlFontProvider.RegisterDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/fonts/"))
Dim cssAppliers As CssAppliers = New CssAppliersImpl(xmlFontProvider)
Dim htmlContext As HtmlPipelineContext = New HtmlPipelineContext(cssAppliers)
htmlContext.SetAcceptUnknown(True)
htmlContext.SetTagFactory(tagProcessors)
Dim pdf As ElementHandlerPipeline = New ElementHandlerPipeline(elements, Nothing)
Dim htmlp As HtmlPipeline = New HtmlPipeline(htmlContext, pdf)
Dim css As CssResolverPipeline = New CssResolverPipeline(cssResolver, htmlp)
Dim worker As XMLWorker = New XMLWorker(css, True)
Dim p As XMLParser = New XMLParser(worker)
'Dim holderTable As New PdfPTable({1})
Dim holderTable As PdfPTable = New PdfPTable({1})
holderTable.WidthPercentage = 100
holderTable.HorizontalAlignment = Element.ALIGN_LEFT
Dim holderCell As New PdfPCell()
holderCell.Padding = 0
holderCell.UseBorderPadding = False
holderCell.Border = 0
p.Parse(New MemoryStream(System.Text.Encoding.ASCII.GetBytes(htmlcode)))
For Each el As IElement In elements
holderCell.AddElement(el)
Next
holderTable.AddCell(holderCell)
'Dim holderRow As New PdfPRow({holderCell})
'holderTable.Rows.Add(holderRow)
Return holderTable
End Function
End Class
Public Class CustomImageTagProcessor
Inherits iTextSharp.tool.xml.html.Image
Public Overrides Function [End](ctx As IWorkerContext, tag As Tag, currentContent As IList(Of IElement)) As IList(Of IElement)
Dim attributes As IDictionary(Of String, String) = tag.Attributes
Dim src As String = String.Empty
If Not attributes.TryGetValue(iTextSharp.tool.xml.html.HTML.Attribute.SRC, src) Then
Return New List(Of IElement)(1)
End If
If String.IsNullOrEmpty(src) Then
Return New List(Of IElement)(1)
End If
If src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase) Then
' data:[<MIME-type>][;charset=<encoding>][;base64],<data>
Dim base64Data As String = src.Substring(src.IndexOf(",") + 1)
Dim imagedata As Byte() = Convert.FromBase64String(base64Data)
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagedata)
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
Else
If File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src)) Then
Dim imagedata As Byte() = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, src))
Dim list As List(Of IElement) = New List(Of IElement)()
Dim htmlPipelineContext As pipeline.html.HtmlPipelineContext = GetHtmlPipelineContext(ctx)
list.Add(GetCssAppliers().Apply(New Chunk(DirectCast(GetCssAppliers().Apply(image, tag, htmlPipelineContext), iTextSharp.text.Image), 0, 0, True), tag, htmlPipelineContext))
Return list
End If
Return MyBase.[End](ctx, tag, currentContent)
End If
End Function
End Class
I highly recommend just using AngleSharp to parse the HTML, edit the document if required, and save it again.
There are many posts on here about why trying to parse HTML with regular expressions is a bad idea.
var doc = new HtmlParser().Parse(html);
As you aren't actually changing the HTML content, just fixing up the tags, your should be able to just parse it and save it with no changes to fix the tags.
This question already has answers here:
Vb.Net convert StrDup to C#.net
(3 answers)
Closed 7 years ago.
Hello I have a code that use with VB.net:
Public Shared Function GetNextID(ByVal Prefix As String) As String
Dim dt As DataTable = Database.GetDataTable("select * from _NumberGeneration Where Entity = '" & Prefix & "'")
If dt Is Nothing OrElse dt.Rows.Count = 0 Then Return ""
Dim format As String = dt.Rows(0)("Format") & ""
Dim sqlCnt As String = dt.Rows(0)("SQL") & ""
Dim cnt As Int32 = Val(Database.ExecuteScalar(sqlCnt)) + 1 ' 11
Dim RN As String = format.Substring(format.IndexOf("["c), 4) ' [R5]
Dim newRN As String = StrDup(CInt(RN.Substring(2,1), "0"c) ' 00000
newRN = cnt.ToString(newRN) ' String.Format(newRN, cnt) ' 00011
Dim newformat As String = format.Replace(RN, newRN) '"PR"yyMM00011
Return Today.ToString(newformat) ' String.Format(newformat, cnt)
End Function
For the StrDup When I write the code with C# same as code below:
string newRN = new string (int.Parse(RN.Substring(2, 1)),'0');
It show the error.
Use the string constructor with character and count parameters:
string newRN = new string('0', 4);
You could also reference the Microsoft.VisualBasic assembly and call the method via the Strings module, but the alternative above is pretty simple.
i am using Visual Studio .NET (VB)
So if you have a solution in C#, just go here first (http://converter.telerik.com/)
I have a document with text, and an array of words to replace:
I need to replace the plaintext and substitute with actual mergefield
Dim replacements(,) As String =
New String(,) {{"[firstname]", "$Field.FName"},
{"[lastname]", "$Field.LName"},
{"[addr]", "$Field.Addr.St"},
{"[city]", "$Field.City"}}
Dim dotXLoc "c:/test/result.dotx"
Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate 'SAVE AS DOT
Dim wordApp As Object = New Microsoft.Office.Interop.Word.Application()
Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(dotXLoc)
' Get bounds of the array.
Dim bound0 As Integer = replacements.GetUpperBound(0)
' Loop over all elements.
For i As Integer = 0 To bound0
' Get element.
Dim FieldFind As String = replacements(i, 0)
Dim FieldReplace As String = replacements(i, 1)
'<<< CODE HERE TO REPLACE TEXT WITH MERGEFIELD >>>
Next
currentDoc.SaveAs(dotXLoc & " v2.dotx", Fileformat)
currentDoc.Close()
wordApp.Quit()
Here is the end result
Public sub main()
Dim rtfLoc = "c:/temp.rtf"
Dim dotXLoc = "c:/temp.dotx"
Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate
Dim wordApp As Word.Application = New Microsoft.Office.Interop.Word.Application()
Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(rtfLoc)
TextToMergeField(currentDoc)
currentDoc.SaveAs(dotXLoc, Fileformat)
currentDoc.Close()
wordApp.Quit()
End Sub
we call TextToMergeField(currentDoc) from the main function
this way we can loop through multiple documents and replace all instances
Private Sub TextToMergeField(ByRef currentdoc As Word.Document)
Dim rng As Word.Range
Dim replacements(,) As String =
New String(,) {{"[firstname]", "$Field.FName"},
{"[lastname]", "$Field.LName"},
{"[addr]", "$Field.Addr.St"},
{"[city]", "$Field.City"}}
Dim bound0 As Integer = replacements.GetUpperBound(0)
currentdoc.Activate()
For i As Integer = 0 To bound0
rng = currentdoc.Range
With rng.Find
.Text = replacements(i, 0)
Do While .Execute(Replace:=WdReplace.wdReplaceOne)
currentdoc.Fields.Add(rng, WdFieldType.wdFieldMergeField, replacements(i, 1))
Loop
End With
Next
End Sub
Hope this helps someone
I'm trying to convert a DTS process to SSIS and I want to convert a DTS script task that creates 3 files (only creates the file if there’s data to write to it) and then appends the full file names to a variable, which is then copied to a global variable. Since I'm new to this I would like a step by step demonstation if possible, Please, Please, Pretty Please help...Thanks. Below is an example of the DTS script that creates two instead of three files:
Function Main()
DIM dbConnection, rsGetFileDetails, rsGetInfo
DIM fsoFileSystem, fExportFile
DIM sGroupCode, sSequenceNumber, sFileIdentifier, FileName
DIM sLineItem, sAttachmentPaths
DIM FileLocation
sAttachmentPaths = ""
FileLocation = DTSGlobalVariables("FileDestPath").Value
'****************************************************
'*********Connect to Database******************
'****************************************************
SET dbConnection = CreateObject( "ADODB.Connection" )
dbConnection.Provider = "sqloledb"
dbConnection.Properties("Data Source").Value = "Server"
dbConnection.Properties("Initial Catalog").Value = "Database"
dbConnection.Properties("Integrated Security").Value = "1234"
dbConnection.Open
'*******************************************************************
'***********GET TRACE ALERT DELIST DATA************
'*******************************************************************
SET fsoFileSystem = CreateObject( "Scripting.FileSystemObject" )
SET rsGetInfo = CreateObject( "ADODB.recordset" )
sql = "SELECT tblExample1.IDNumber, tblExample2.First_Name, tblExample3.Main_Name FROM tblExample1 INNER JOIN tblExample2 ON tblExample1.IDNumber = tblExample2.Entity_ID_Number WHERE (tblExample1.IDNumber = '2') AND (Process_Date IS NULL)"
rsGetInfo.Open sql, dbConnection
IF rsGetInfo.EOF THEN
ELSE
FileName = "MyFileName_" & Replace( Date() , "/" , "")
'//Create the file
SET fExportFile = fsoFileSystem.CreateTextFile( FileLocation & FileName & ".txt", true )
DTSGlobalVariables("FileLocation").Value = FileLocation & FileName & ".txt"
rsGetInfo.MoveFirst
DO WHILE NOT rsGetInfo.EOF OR rsGetInfo.BOF
sLineItem = ""
sLineItem = rsGetInfo("IDNumber") & vbtab & rsGetDelistInfo("First_Name") & vbtab & rsGetInfo("Main_Name")
fExportFile.Write(sLineItem & vbcrlf)
rsGetInfo.MoveNext
LOOP
'// Set Attachment Path
sAttachmentPaths = FileLocation & FileName & ".txt"
END IF
'*******************************************************************
'***********GET DEFAULT DELIST DATA************
'*******************************************************************
SET fsoFileSystem = CreateObject( "Scripting.FileSystemObject" )
SET rsGetInfo = CreateObject( "ADODB.recordset" )
sql = "SELECT Contract_No FROM tblfunny WHERE (funnyNumb = 1) and (Process_Date IS NULL)"
rsGetInfo.Open sql, dbConnection
IF rsGetInfo.EOF THEN
ELSE
FileName = "MyFileName_" & Replace( Date() , "/" , "")
'//Create the file
SET fExportFile = fsoFileSystem.CreateTextFile( FileLocation & FileName & ".txt", true )
DTSGlobalVariables("FileLocation").Value = FileLocation & FileName & ".txt"
rsGetInfo.MoveFirst
DO WHILE NOT rsGetInfo.EOF OR rsGetInfo.BOF
sLineItem = ""
sLineItem = rsGetInfo("Contract_No")
fExportFile.Write(sLineItem & vbcrlf)
rsGetInfo.MoveNext
LOOP
'// Set Attachment Path
IF sAttachmentPaths = "" THEN
sAttachmentPaths = FileLocation & FileName & ".txt"
ELSE
sAttachmentPaths = sAttachmentPaths & "; "& FileLocation & FileName & ".txt"
END IF
END IF
Main = DTSTaskExecResult_Success
End Function