Inserting rows into existing Excel worksheet with OleDbConnection - oledb

I'm building insert statements based on a list of data and a tab name. I have 4 tabs, the last 2 get data inserted successfully, the first 2 do not.
I commented out inserting into all tabs but one. The size of the excel file increases, but the rows are still blank. Any ideas?
Edit: For some reason, the Excel file I was using as a "blank template" had "empty" values in rows of the first 2 sheets. First one had "empty values" in the first 100K rows, seconds had empty values in the first 700-some rows. The data was being inserted after these rows, which explains why the file size was increasing. Now I'm getting "Operation must use an updateable query" when trying to insert.
Public Sub BuildReport(Of T)(tabName As String, dataList As IEnumerable(Of T))
'// Setup the connectionstring for Excel 2007+ XML format
'// http://www.connectionstrings.com/ace-oledb-12-0/
If ((tabName.EndsWith("$") = True AndAlso m_TabList.Contains(tabName) = False) OrElse m_TabList.Contains(tabName & "$") = False) Then
Throw New Exception(String.Format("The specified tab does not exist in the Excel spreadsheet: {0}", tabName))
End If
Using excelConn As New OleDbConnection(m_ConnectionString)
excelConn.Open()
Dim insertStatementList As IEnumerable(Of String) = BuildInsertStatement(Of T)(tabName, dataList)
Using excelCommand As New OleDbCommand()
excelCommand.CommandType = CommandType.Text
excelCommand.Connection = excelConn
For Each insertStatement In insertStatementList
excelCommand.CommandText = insertStatement
excelCommand.ExecuteNonQuery()
Next
End Using
End Using
End Sub
Private Function BuildInsertStatement(Of T)(tabName As String, dataList As IEnumerable(Of T)) As IEnumerable(Of String)
Dim insertStatementList As New List(Of String)
Dim insertStatement As New StringBuilder()
For Each dataItem As T In dataList
Dim props As PropertyInfo() = GetType(T).GetProperties()
insertStatement.Clear()
insertStatement.AppendFormat("INSERT INTO [{0}$] ", tabName)
Dim nameValueDictionary As New Dictionary(Of String, String)
For Each prop As PropertyInfo In props
Dim excelColumn As ExcelColumnAttribute = CType(prop.GetCustomAttributes(GetType(ExcelColumnAttribute), False).FirstOrDefault(), ExcelColumnAttribute)
If (excelColumn IsNot Nothing) Then
Dim value As Object = prop.GetValue(dataItem, Nothing)
If (value IsNot Nothing AndAlso value.GetType() <> GetType(Integer) _
AndAlso value.GetType() <> GetType(Double) _
AndAlso value.GetType() <> GetType(Decimal) _
AndAlso value.GetType() <> GetType(Boolean)) Then
value = String.Format("""{0}""", value)
ElseIf (value Is Nothing) Then
value = "NULL"
End If
nameValueDictionary.Add(excelColumn.ColumnName, value)
End If
Next
Dim columList As String = String.Join(",", nameValueDictionary.Keys)
Dim valueList As String = String.Join(",", nameValueDictionary.Select(Function(x) x.Value))
insertStatement.AppendFormat("({0}) ", columList)
insertStatement.AppendFormat("VALUES ({0})", valueList)
insertStatementList.Add(insertStatement.ToString())
Next
Return insertStatementList
End Function

For some reason, the Excel file I was using as a "blank template" had "empty" values in rows of the first 2 sheets. First one had "empty values" in the first 100K rows, second one had empty values in the first 700-some rows. The data was being inserted after these rows, which explains why the file size was increasing. Now I'm getting "Operation must use an updateable query" when trying to insert.
I found the answer to the second problem here: Operation must use an updateable query when updating excel sheet
Just needed to remove the "IMEX=1" from the extended properties of the connection string which I added in trying to troubleshoot the issue.

Related

Truncated message tweets

Please!
I'm getting tweets from LinqToTwitter, and some tweets seem to have the text truncated, with part of the text following with an ellipsis. In some cases, the search criteria are not returned in the text, as it appears to be in the unearned part of the message. That's right? Is there a way to get this missing part of the message? I have already looked at other posts, but I could not understand which parameter allows the full text to be obtained. I'm using linqToTwitter version 4.1.0.
Thank you
Dim twitterCtx As TwitterContext = New TwitterContext(twAuth)
Dim Response As Search = Await (From search In twitterCtx.Search()
Where search.Type = SearchType.Search _
AndAlso search.SearchLanguage = "pt" _
AndAlso search.Query = "Coronavirus").SingleOrDefaultAsync()
Dim tweets As List(Of Status) = Response.Statuses()
If Response IsNot Nothing AndAlso Response.Statuses IsNot Nothing Then
For Each str As Status In tweets
Console.WriteLine(str.StatusID.ToString() + " " + str.Text)
Next
End If
When Twitter extended tweets from 140 to 280 characters, they needed to add support in the API. This is called Extended Mode and you need to add a new filter to your LINQ query, like this:
Dim Response As Search = Await (From search In twitterCtx.Search()
Where search.Type = SearchType.Search _
AndAlso search.SearchLanguage = "pt" _
AndAlso search.TweetMode = TweetMode.Extended _
AndAlso search.Query = "Coronavirus").SingleOrDefaultAsync()
Notice the search.TweetMode property. I assigned the TweetMode.Extended enum to it, which means you now get the full 280 characters.
Having done that, you might view the Text property and be surprised to see Nothing. That's because now the tweet text is in the FullText property and you can read it like this:
Dim tweets As List(Of Status) = Response.Statuses()
If Response IsNot Nothing AndAlso Response.Statuses IsNot Nothing Then
For Each str As Status In tweets
Console.WriteLine(str.StatusID.ToString() + " " + str.FullText)
Next
End If

Exclude suppressed fields from Sum

I need your help in excluding the suppressed amounts from the SUM in the group footer. In the details section, I am having duplicate deal no and amounts.So, in the Section Expert for the details sections, I performed a condition on the formula "Suppress" to suppress the duplicated fields which is:
{deal_no} = (next{deal_no})
The above condition is applied in the report and I was able to suppress the duplicates. Now in the group footer, I am performing a running total using the formulas to calculate the SUM for the amounts. However, this SUM is calculating the suppressed amounts and it is giving the results. So how to remove them from the calculation.
This is the answer
WhilePrintingRecords;
If {deal_no} <> (next{deal_no}) OR OnLastRecord then //this excludes the duplicates
(
numbervar gsum := gsum + {#Cost};
numbervar grand := grand + gsum;
);
what you can do is instead of using running total you can just summarize by right clicking on the field and using Insert Summary which will give correct result.
I have made function funsumColumn(dtfunSum, "intProductId", "decCBMCMS")
and pass datattable, table id name, and column name that i want to sum to.
This function returns sum of unique id row.
Private Function funsumColumn(ByVal dt As DataTable, ByVal idColumnName As String, ByVal ColumnForSum As String) As Decimal
Dim dtnew As New DataTable
dtnew.Columns.Add(idColumnName, GetType(Integer))
dtnew.Columns.Add(ColumnForSum, GetType(Double))
Dim dtMainTable As DataTable
Dim ComputeColumnSum As Decimal
Try
Dim ExistIdInLocalTable As Integer
Dim foundRow() As DataRow
Dim PIid As Integer
For i As Integer = 0 To dt.Rows.Count - 1
PIid = dt.Rows(i).Item(idColumnName)
foundRow = dtnew.Select("" & idColumnName & "='" & PIid & "'")
ExistIdInLocalTable = foundRow.Count
If foundRow.Count = 0 Then
dtnew.Rows.Add(dt.Rows(i).Item(idColumnName), dt.Rows(i).Item(ColumnForSum))
Else
End If
Next
dtMainTable = dtnew
ComputeColumnSum = dtMainTable.Compute("sum(" & ColumnForSum & ")", "")
Return ComputeColumnSum
Catch ex As Exception
End Try
Return ComputeColumnSum

about split command in string using vb.net

am having url .it contain the querstring value like this.to split the url and store the querystring values in an array .query string values are not passed with in application .
it comes from another application
url
----
http://.....?lead_id=152818&vendor_id=100001&list_id=1001&gmt_offset_now=0.00&phone_code=91&phone_number=9942321400&title=MR&first_name=Hari&middle_initial=Q&last_name=PUBLIC&address1=249+MUNDON+ROAD&address2=MALDON&address3=FL&city=44&state=TN&province=NO_PROVINCE&postal_code=600004&country_code=IN&gender=M&date_of_birth=0000-00-00&alt_phone=9942321400&email=test#test.com&security_phrase=nothing&comments=COMMENTS&user=22222&pass=test&campaign=OUTBOUND&phone_login=22222&original_phone_login=22222&phone_pass=test&fronter=22222&closer=22222&group=OUTBOUND&channel_group=OUTBOUND&SQLdate=2012-08-07+164931&epoch=1344338372&uniqueid=1344338352.12754&customer_zap_channel=&customer_server_ip=&server_ip=10.103.200.177&SIPexten=22222&session_id=8600062&phone=9942321400&parked_by=152818&dispo=N&dialed_number=9942321400&dialed_label=MAIN&source_id=10001&rank=1&owner=Southeast&camp_script=&in_script=&script_width=600&script_height=340&fullname=J.Hariharan&recording_filename=OUTBOUND_20120807-164911_22222_9942321400&recording_id=248601&user_custom_one=&user_custom_two=&user_custom_three=&user_custom_four=&user_custom_five=&preset_number_a=&preset_number_b=&preset_number_c=&preset_number_d=&preset_number_e=&preset_dtmf_a=&preset_dtmf_b=&session_name=1344338181_2222216466857"
my question is i want to store the querystring values in an one dimensional string
array.
my code
-------
Dim strarr() As String
Dim s As String = "http://...../test.aspx?lead_id=152818&vendor_id=100001&list_id=1001&gmt_offset_now=0.00&phone_code=91&phone_number=9942321400&title=MR&first_name=Hari&middle_initial=Q&last_name=PUBLIC&address1=249+MUNDON+ROAD&address2=MALDON&address3=FL&city=44&state=TN&province=NO_PROVINCE&postal_code=600004&country_code=IN&gender=M&date_of_birth=0000-00-00&alt_phone=9942321400&email=test#test.com&security_phrase=nothing&comments=COMMENTS&user=22222&pass=test&campaign=OUTBOUND&phone_login=22222&original_phone_login=22222&phone_pass=test&fronter=22222&closer=22222&group=OUTBOUND&channel_group=OUTBOUND&SQLdate=2012-08-07+164931&epoch=1344338372&uniqueid=1344338352.12754&customer_zap_channel=&customer_server_ip=&server_ip=10.103.200.177&SIPexten=22222&session_id=8600062&phone=9942321400&parked_by=152818&dispo=N&dialed_number=9942321400&dialed_label=MAIN&source_id=10001&rank=1&owner=Southeast&camp_script=&in_script=&script_width=600&script_height=340&fullname=J.Hariharan&recording_filename=OUTBOUND_20120807-164911_22222_9942321400&recording_id=248601&user_custom_one=&user_custom_two=&user_custom_three=&user_custom_four=&user_custom_five=&preset_number_a=&preset_number_b=&preset_number_c=&preset_number_d=&preset_number_e=&preset_dtmf_a=&preset_dtmf_b=&session_name=1344338181_2222216466857"
strarr = s.Split("?")
Dim s1 As String = strarr(1)
Dim constr() As String
constr = s1.Split("&")
but am not get correct result
my result
---------
list_id=1001
gmt_offset_now=0.00
phone_code=91
phone_number=9942321400
expected result
---------------
1001
0.00
91
9942321400
Iterate over your 'constr' and use one more split ( by '=' ). Results can be stored in List(of String).
dim r as new list(of String)
for each c in constr
r.add(c.split("=")(1))
next
(something like this)
To view this you should list all items inside 'r', so you'll need another for.
for each item in r
console.writeline(item)
next
You can do it inside first loop either.

LINQ concatenate 2 fields to search on

I'm trying to concatenate two fields in LINQ so that I can then filter with a keyword. I found a question posted here that I thought was my answer, but I'm getting 0 records back for some reason. This is supposed to return a JSON result for an autocomplete textbox (it works when I don't concatenate fields).
Here's my code:
Function CostCodeList(ByVal term As String) As ActionResult
Dim results = From c In db.ORG_CHART_V
Let Fullname = CStr(c.COSTCTR_CD & " - " & c.BREADCRUMB)
Where Fullname.ToUpper.Contains(CStr(term).ToUpper)
Order By Fullname
Select New With {.label = Fullname, .id = c.ORG_NODE_ID}
Return Json(results.ToArray, JsonRequestBehavior.AllowGet)
End Function
I'm also getting this error on the Return:
Public member 'ToArray' on type 'DbQuery(Of VB$AnonymousType_3(Of
String,Integer))' not found.
Before trying to concatenate the two fields I was searching on them separately, successfully. But when I concatenate them, it seems like everything I try either gets me an error and/or zero records.
Here is a different function that does work:
Function RoleList(ByVal term As String) As ActionResult
Dim list As New ArrayList
Dim results As IQueryable(Of JOB_ROLE)
If IsNumeric(term) Then
results = From c In db.JOB_ROLE
Where CStr(c.JBROLE_NO).StartsWith(term)
Else
results = From c In db.JOB_ROLE
Where c.JOB_ROLE_NAME.ToUpper.Contains(CStr(term).ToUpper)
End If
results = results.OrderBy(Function(e) e.JOB_ROLE_NAME)
For Each item In results
list.Add(New With {.label = item.JOB_ROLE_NAME, .id = item.JOB_ROLE_ID})
Next
Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
End Function
Here is the new function that works as intended:
Function CostCodeList(ByVal term As String) As ActionResult
Dim list As New ArrayList
Dim results = db.ORG_CHART_V.Where(Function(e) (CStr(e.COSTCTR_CD) + " - " + e.BREADCRUMB).Contains(CStr(term).ToUpper)).OrderBy(Function(o) o.COSTCTR_CD)
For Each item In results
list.Add(New With {.label = item.COSTCTR_CD & " - " & item.BREADCRUMB, .id = item.ORG_NODE_ID})
Next
Return Json(list.ToArray, JsonRequestBehavior.AllowGet)
End Function

Creating a List (of String) giving error" Object reference not set to an instance of an object. "

MVC 3 razor VB.NET project. I have resorted to manual building a list for a drop down box so I can insure certain values are available in the select list and also to control what the first item is in the list. The below is my code snippet for the part that is giving me problems..
Dim _courses1 As Integer = db.courses.ToList.Where(Function(r) r.course_day = "Tuesday").Count
Dim _classes1 As List(Of cours) = db.courses.ToList
Dim classRef1 As List(Of String)
If Not _selectedClass0 = "--" Then
classRef1.Add("--")
Else
classRef1.Add(_selectedClass0)
End If
For i As Integer = 0 To _courses1 - 1
For Each item In _classes1.Where(Function(f) f.course_day = "Tuesday")
Dim _item As cours = item
classRef1.Add(_item.course_ref)
Next
Next
ViewBag.tue1 = classRef1
The _selectedClass0 is just a string that gets set earlier... The error mentioned happens when it gets to the ClassRef1.Add(_selectedClass0) part of the else statement. Which _selectedClass0 string value at the time of error is "--". I have a feeling it is in how the list is being created but I am not certain... Any ideas???
You're not initializing classRef1.
Dim classRef1 As new List(Of String)
Another thing I see is in the first line - I've made the changes I see:
Dim _courses1 As Integer = db.courses.Where(Function(r) r.course_day = "Tuesday").Count()
You don't need ToList at the beginning if all your getting is the count.
You are declaring classRef1 to be a list of strings here:
Dim classRef1 As List(Of String)
But you're never actually creating an instance using New. I'm not sure about the VB syntax, as I'm a C# developer, but I'd guess you should add the following line right after the declaration:
classRef1 = New List(Of String)

Resources