How I read XLMS file row by row after a condition? - asp.net

I have a problem with a XLSM Excel of which I want to get some data by condition.
Excel image
In the picture I have "Name", and "Status", if the status is "Completed" I want to take their value on "Time Assembly -> Post Assembly" where the value is "1.11". For each value of "Time Assembly" in the end I want to do media.
my code:
If FileUpload1.HasFile = False Then
Exit Sub
Else
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")
Dim FilePath As String = Server.MapPath("~") & "\Upload\" & FileName
FileUpload1.SaveAs(FilePath)
Dim existingFile = New FileInfo(FilePath)
Dim pack As ExcelPackage = New ExcelPackage(existingFile)
Dim workBook As ExcelWorkbook = pack.Workbook
If workBook.Worksheets.Count > 0 Then
Dim currentWorksheet As ExcelWorksheet = workBook.Worksheets.First()
End If
End If
In that "if" I want to read Excel row by row, after that condition.
Thanks a lot!

Try to find the last row in the sheet and use for loop to iterate the condition
Sub test()
Dim lastRow As Long
Dim workBook As workBook
workBook = ThisWorkbook
lastRow = workBook.ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To lastRow
'for checking value in the 4 column(D column)
If (workBook.ActiveSheet.Cells(i, 4).Value) = "completed" Then
workBook.ActiveSheet.Cells(i, 6).Value = "xx"
End If
'for adding value in the 6 column
Next
End Sub

Related

Formatting a column to use a phone number format in EPPlus

I have phone numbers stored as a string of numbers, e.g.: 6028035615, but CAST them as integers when querying. I want to format the data in the cell in proper phone number format, such as (602) 803-5615 as Excel would. But how do I state the format type I want to use?
If I use:
objData.Columns.Add("HPhone", GetType(Integer))
wshUS.Column(i).Width = 15 ' PhoneH
wshUS.Column(i).Style.Numberformat.Format = "###-###-####"
or
wshUS.Column(i).Style.Numberformat.Format = "(###) ###-####"
a blank cell is shown as either -- in the former case or ()- in the latter.
Is there a format type that I can put after the = to get phone numbers as Excel would?
How would I use conditional formatting to overcome that problem?
I am writing in VB.NET in codebehind for web pages.
What is objData? Generally speaking, you shouldn't need to add columns to a sheet - EPPlus will do this automatically when your reference the cell for the first time. My VB is a little rusty but this works fine for me:
<TestMethod> _
Public Sub PhoneNumberFormatTest()
Dim file = New FileInfo("c:\temp\temp.xlsx")
If file.Exists Then
file.Delete()
End If
Dim pck = New ExcelPackage(file)
Dim workbook = pck.Workbook
Dim worksheet = workbook.Worksheets.Add("newsheet")
Const number As String = "6028035615"
Const format As String = "(###) ###-####"
Dim startcell = worksheet.Cells(1, 1)
startcell.Value = Int64.Parse(number)
startcell.Offset(1, 0).Value = Int64.Parse(number) + 1
worksheet.Column(1).Width = 15
worksheet.Column(1).Style.Numberformat.Format = format
pck.Save()
End Sub
I downloaded the source code solution of EPPlus 3 (stable) and ran this as a unit test...
EDIT: Added string manipulation:
<TestMethod> _
Public Sub PhoneNumberFormatTest()
Dim file = New FileInfo("c:\temp\temp.xlsx")
If file.Exists Then
file.Delete()
End If
Dim pck = New ExcelPackage(file)
Dim workbook = pck.Workbook
Dim worksheet = workbook.Worksheets.Add("newsheet")
Const number As String = "6028035615"
Const format As String = "(###) ###-####"
Dim startcell = worksheet.Cells(1, 1)
'Directly to numbers with parse
startcell.Value = Int64.Parse(number)
startcell.Offset(1, 0).Value = Int64.Parse(number) + 1
'OR as a string back to a number.
Dim stringcell = startcell.Offset(2, 0)
stringcell.Value = number
stringcell.Value = Int64.Parse(DirectCast(stringcell.Value, String))
stringcell.Style.Numberformat.Format = "(###) ###-####"
'As string - does not work as number
stringcell.Offset(0, 1).Value = number
stringcell.Offset(0, 1).Style.Numberformat.Format = "(###) ###-####"
worksheet.Column(1).Width = 15
worksheet.Column(1).Style.Numberformat.Format = format
pck.Save()
End Sub
The exact formatting that excel use for phone numbers is: "[<=9999999]###-####;(###) ###-####".
I suggest you also check this answer: EPPlus Format Cell as "Accounting" Number. It shows how to get all built-in formatting formula.

asp vb save excel file in particular path

refering to this link Creating an Excel Application from VB.Net
I want to save my excel file to this path:
C:\Users\asdfme\Documents
with the filename format [PROJ_DATE].xls example:PROJ_20140703.xls
here is my code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Call temporaryValue()
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
Dim strPathExcel As String
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
appXL.Visible = True
' Add a new workbook.
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
' Add table headers going cell by cell.
Dim heads() As String = {"", "MONo", "PostingDate", "DocDate", "SBU", "Operation", "Resource", "TimeType", "StartDate", "StartTime", "EndDate", "EndTime", "NoofResources", "Remarks", "Quantity", "Rejects"}
For head1 As Integer = 1 To 15
shXL.Cells(1, head1).Value = heads(head1)
Next
Dim body() As String = {"", txtmo.Text, PostingDate, DocDate, SBU, Operation, Session("user"), (ddltype.SelectedValue).ToUpper, lblsDate.Text, lblsTime.Text, lbleDate.Text, lbleTime.Text, no_ofres, lblrem.Text, txtgoods.Text, txtrejects.Text}
For body1 As Integer = 1 To 15
shXL.Cells(2, body1).Value = body(body1)
Next
appXL.Visible = True
appXL.UserControl = True
' Release object references.
wbXl.SaveAs(Filename:="C:\Users\asdfme\Documents\PROJ_20140703.xls")
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL.Quit()
appXL = Nothing
Exit Sub
Err_Handler:
MsgBox(Err.Description, vbCritical, "Error: " & Err.Number)
End Sub
when i run this code,
it only create an excel file and ask me if i want to save the file.
what i want is whenever i run this, the file will save with the file name format (written above) in the path i declare.
Please help. thank you
Dim myXlsFileName As String = "PROJ_" & " " & Format(Now.Date, "yyyyddMM") & ""
wbXl.SaveAs(Filename:="C:\Documents and Settings\All Users\Desktop\" & myXlsFileName & ".xls")

How to limit the number of rows to be read in a CSV file using CSVReader in ASP.NET

I am using a csvReader in order to retrieve data from a csv file. My csv file consists of 500elements and I only need the first 300. How do I limit my csvReader in order to return only 300 elements?
Dim PressureTable As DataTable = GetDataTabletFromCSVFile(BackUpDirDminus1)
Console.WriteLine("Rows count:" + PressureTable.Rows.Count.ToString)
Console.ReadLine()
Using CSVReader As New TextFieldParser(BackUpDirDminus1)
CSVReader.SetDelimiters(New String() {","})
CSVReader.HasFieldsEnclosedInQuotes = True
'read column names
Dim colFields As String() = CSVReader.ReadFields()
'For Each column As String In colFields
While Not CSVReader.EndOfData
Dim fieldData As String() = CSVReader.ReadFields()
'Making empty value as null
For i As Integer = 0 To fieldData.Length-1
If fieldData(i) = "" Then
fieldData(i) = Nothing
End If
Next
PressureTable.Rows.Add(fieldData)
End While
End Using
Please help. Thanks
I suppose there should be a method name "ReadNextRecord()", so your while loop should be like
While CSVReader.ReadNextRecord()
Declare a int k =0
and do k++
Once K++ reaches 300, then you can End While.

Cannot get the last row of data

In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

Resources