In my project I am creating a CSV file, but I want to change it's design. Please help me:
Private Sub ExportDataToCSV()
Dim fileName As String = "CheckRegistrationStatus_" & Format(Now, "yyyyMMddhhmms") & ".csv"
HttpContext.Current.Response.Clear()
' Set the response headers to fit our CSV file
HttpContext.Current.Response.ContentType = "text/plain"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
Using writer As New System.IO.StreamWriter(HttpContext.Current.Response.OutputStream)
Dim columnHeader As String = String.Empty
For i As Integer = 0 To grd1.Columns.Count - 1
columnHeader += grd1.Columns(i).HeaderText & IIf(i < grd1.Columns.Count - 1, ",", "").ToString()
Next
writer.WriteLine(columnHeader)
'writer.WriteLine(AddCSVHeaderRow()) ' Only if you need custom headers to be added
' Add all the data rows
For Each row As GridViewRow In grd1.Rows
writer.WriteLine(GetCSVLine(row.Cells))
Next
End Using
' End the current response. Otherwise, excel will open with the whole page inside.
HttpContext.Current.Response.End()
End Sub
Private Shared Function GetCSVLine(ByVal cellsToAdd As TableCellCollection) As String
Dim line As String = String.Empty
Dim isFirst As Boolean = True
For Each cell As TableCell In cellsToAdd
If Not isFirst Then
line += ","
End If
isFirst = False
line += """" & Replace(cell.Text, " ", "") & """"
Next
Return line
End Function
Output is being displayed as shown in the following image. But I want to make the header bold and expand the column width . Please help me.
You cannot. The CSV file format is a data-only format. It provides no way to set fonts, column widths or anything else related to styling.
In addition, I don't think your code handles all data correctly. For example, if there's a comma within the data or a double quote, special steps are required. Here's some code I published for creating CSV files in C#.
If you want to produce a formatted Excel document, either in addition to your CSV file or in place of it, you could have a look at the Excel interop libraries.
http://msdn.microsoft.com/en-us/library/bb386107%28v=vs.90%29.aspx
http://support.microsoft.com/kb/301982
http://msdn.microsoft.com/en-us/library/aa188489%28office.10%29.aspx
Related
Hi I am having some problems with saving img files using Visual Basic, the files are being named wrongly with the folder name being added to the start of the file name.
I parse a web address and then use the split address values to rename my files however the the path value seems to be added to the file as well.
The files in the photo should be named for example "DCAT040iMBE Test13.jpg"
but this file is being name "Test1DCAT040iMBE Test13.jpg"
Protected Sub GeneratedCode()
Dim path As String = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\"
LogoUpload.SaveAs(path + LogoUpload.FileName)
TextFile.SaveAs(path + TextFile.FileName)
Dim lines() As String = IO.File.ReadAllLines(path + TextFile.FileName)
For Each line As String In lines
Dim count As Integer
Dim encoder As New QRCodeEncoder()
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
encoder.QRCodeScale = 10
Dim img As Bitmap = encoder.Encode(line)
Dim logo As System.Drawing.Image = System.Drawing.Image.FromFile(path + LogoUpload.FileName)
Dim left As Integer = (img.Width / 2) - (logo.Width / 2)
Dim top As Integer = (img.Height / 2) - (logo.Height / 2)
Dim g As Graphics = Graphics.FromImage(img)
Dim parseLine = line
Dim replaceDelimiter As String
If Not String.IsNullOrWhiteSpace(line) Then
replaceDelimiter = Replace(line, "&", "=")
End If
Dim fileNameSplit() As String = replaceDelimiter.Split("=")
Dim newFileName As String
Dim partTwo = fileNameSplit(1)
Dim partSix = fileNameSplit(5)
Dim objFSO
Dim newFolder As String
newFolder = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\" + partSix
objFSO = CreateObject("Scripting.FileSystemObject")
If (Not System.IO.Directory.Exists(newFolder)) Then
System.IO.Directory.CreateDirectory(newFolder)
End If
count += 1
g.DrawImage(logo, New Point(left, top))
newFileName = partTwo & " " & partSix & count & ".jpg"
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
amountCreatedLbl.Text = count & " QRCodes Created"
logo.Dispose()
Next
End Sub
Could it be that I am generating my newFolder Values wrongly?
edited to add an example of data from the parsed txt file.
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test
Looks like you are missing a slash on the line:
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
It should be:
img.Save(newFolder + "\" + newFileName, ImageFormat.Jpeg)
The program doesn't realize that the newDirectory variable is supposed to be a directory, it's just being concatenated to the filename directly. A better option would be to use:
img.Save(System.IO.Path.Combine(newFolder, newFileName), ImageFormat.Jpeg)
The System.IO.Path.Combine() function automatically adds the missing slash between the directory and filename, as well as some additional checks to make sure the result is valid.
As a side note, I would also recommend using & instead of + when joining strings together. Hard to debug issues can come up when you do it that way. I would also recommend turning Option Strict On, you will see a couple of other warnings that come up with your code as is. But, to resolve your issue, the above will work.
I created a VB script to recursively list all of its file and subfolder files. The script begins fine but eventually crashes in any folder containing a file with a non-printable character/s in their filenames, i.e. I see little squares when I browse the folder in Explorer. I'm not sure how to change my below error handling to continue when it finds a file with such characters.
Any advice or solutions would be appreciated. Thank you.
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "C:\Input\"
Set objFolder = objFSO.GetFolder(strFolder)
Set NewFile = objFSO.CreateTextFile("C:\Output\" & objFolder.Name & " FileList.txt", True)
Set colFiles = objFolder.Files
On Error Resume Next
For Each objFile In colFiles
NewFile.WriteLine(objFile.Path)
If Err Then
Err.Clear
End If
Next
ShowSubFolders(objFolder)
Sub ShowSubFolders(objFolder)
Set colFolders = objFolder.SubFolders
For Each objSubFolder In colFolders
Set colFiles = objSubFolder.Files
For Each objFile In colFiles
NewFile.WriteLine(objFile.Path)
If Err Then
Err.Clear
End If
Next
ShowSubFolders(objSubFolder)
Next
End Sub
NewFile.Close
Create the output text file as unicode so it can handle "non printable" characters. Third parameter of CreateTextFile.
Set NewFile = objFSO.CreateTextFile(" ... ", True, True)
EDITED
If you can not work with unicode files, then file/folder names should be converted from unicode to ansi before writing to output file. This will do the conversion
Function Unicode2Ansi( text )
Unicode2Ansi = text
With (WScript.CreateObject("ADODB.Stream"))
' Put data into stream
.Type = 2 '( adTypeText )
.Charset = "x-ansi"
.Open
.WriteText text
'Retrieve data from stream
.Position = 0
Unicode2Ansi = .ReadText
.Close
End With
End Function
And adapt code to call it NewFile.WriteLine Unicode2Ansi(objFile.Path)
I'm creating an excel file using the response object in an asp.net web application. Some of the long numeric values are being converted to scientific notation. I would like to keep the code I'm using because it prevents time-out issues I received due to the size of the data. Can someone offer any advice on how to modify the existing code to prevent columns from being converted to scientific notation?
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=test.csv")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.xls"
Try
sqlconn.Open()
Dim dr As SqlDataReader = sqlcmd.ExecuteReader()
Dim sb As New StringBuilder()
'Add Header
For count As Integer = 0 To dr.FieldCount - 1
If dr.GetName(count) IsNot Nothing Then
sb.Append(dr.GetName(count))
End If
If count < dr.FieldCount - 1 Then
sb.Append(",")
End If
Next
Response.Write(sb.ToString() & vbLf)
Response.Flush()
'Append Data
While dr.Read()
sb = New StringBuilder()
For col As Integer = 0 To dr.FieldCount - 2
If Not dr.IsDBNull(col) Then
sb.Append(dr.GetValue(col).ToString().Replace(",", " "))
End If
sb.Append(",")
Next
If Not dr.IsDBNull(dr.FieldCount - 1) Then
sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "))
End If
Response.Write(sb.ToString() & vbLf)
Response.Flush()
End While
dr.Dispose()
Catch ex As Exception
Finally
sqlconn.Close()
End Try
Response.End()
As far as I know, the issue is happening because Excel is reading your data and guessing at what type of data it is and if it thinks they are numbers for things that are really text with numbers in it, then it starts applying scientific notation.
The only way I know of to force this to not happen is to use the Excel API and force a column to a particular format, like this:
xlApp.Columns("A:A").Select()
xlApp.Selection.NumberFormat = "#"
Note: This will select column A in your worksheet and then force the number format to text.
Hi I know this question is a bit old but I just want to share my idea on how to prevent the scientific notations in excel generated files. I have tried the "#" but the cells on the respective row/column where I applied the .NumberFormat has a warning icon on it. It says that converting a number to text is invalid.
I have here a solution in which I personally used as a fixed to that warning, you can use a "#" instead "#". Here is the sample.
mySheet.Range("A:A").NumberFormat = "#"
I think using the "#" is for text data type only that is why the warning occurs.
Hope this helps.
I have been trying to save a base64 file as an image from server side using classic ASP. What I want is it to autosave the file to a specific location and give it a filename, Now I am fine coding that aspect of it. However I can't get the code to save the image without first rendering on a browser. This isn't going to work for me as the script I am using will be an automatic export and have no user input.
Code follows as yet that renders in the webpage and asks the user where to save the image. Just to reiterate I need it to auto save (no user input)
base64String ="base64 code goes here - Wont add it as its huge amount of text"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
vehicleAuditName= "Audit1"
With Response
.Clear
.ContentType = "image/png"
.AddHeader "Content-Disposition", "attachment; filename=" & vehicleAuditName & ".png"
.BinaryWrite nodeB64.NodeTypedValue 'get bytes and write
.end
End With
use an adodb.stream object to store the image on the server side like so:
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = adTypeBinary
call bStream.Open()
call bStream.Write( binData )
call bStream.SaveToFile( FullName, adSaveCreateOverWrite)
call bStream.close()
set bStream = nothing
The server side code that receives the base64 string is below, please note that this is code that is taken from a working system so there are variables such as carreg / auditdate that are used as unique identifiers for giving the created file a name:
function convBase64 (convVal, getCarReg, convType, AuditDate, AuditReference)
base64String = convVal
carReg = (UCase(getCarReg))
carReg = (Replace(getCarReg," ",""))
AuditDate= CDate(AuditDate)
ConvAuditDate = ((DatePart("d",AuditDate))& "_" & (DatePart("m",AuditDate)) & "_" & (DatePart("YYYY",AuditDate)))
select case convType
Case "Sig1"
FileNameSuffix = "AuditorsSignature"
Case "Sig2"
FileNameSuffix = "BodyShopSignature"
Case "Car"
FileNameSuffix = "DamageCanvas"
end select
ImageFileName = FileNameSuffix & "-" & carReg & "-" & ConvAuditDate & ".jpg"
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64" ' stores binary as base64 string
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1) ' append data text (all data after the comma)
dim bStream : set bStream = server.CreateObject("ADODB.stream")
bStream.type = 1
call bStream.Open()
call bStream.Write( nodeB64.NodeTypedValue )
call bStream.SaveToFile(Server.Mappath("NoneVehicleImages/" & AuditReference & "/" & ImageFileName), 2 )
call bStream.close()
set bStream = nothing
convBase64 = "\\iis_fdg$\AuditExport\NoneVehicleImages\" & AuditReference & "\" & ImageFileName
end function
You cannot do this due to security reasons. If web pages could randomly choose where to store files on our local systems without any user interaction, there would chaos.
This is a method in ASP Classic that saves a file to disk. It takes a very long time but I'm not sure why. Normally, I wouldn't mind so much, but the files it handles are pretty large so need this needs to faster than 100kB a second save. Seriously slow. (old legacy system, band aid fix till it gets replaced...)
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\" '"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
I'm asking because there are plenty of WTF's in this code so I'm fighting those fires while getting some help on these ones.
I don't see your definition for "FileData" anywhere in your code - where is this coming from? Is there a reason you're writing it to disk a single character at a time? I'd suspect this is your problem - writing 100K of data takes 100K trips through this loop, which could be the reason for your slowdown. Why can't you replace the write loop at the bottom:
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
with a single statement to write the file all at once?
oFile.Write FileData
What you should do is read the binary request into an ADODB.Stream object and convert it to plain ASCII text in a single fast step.
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 1
objStream.Open
objStream.Write Request.BinaryRead(Request.TotalBytes)
objStream.Position = 0
objStream.Type = 2
objStream.Charset = "ISO-8859-1"
FormData = objStream.ReadText
objStream.Close
Set objStream = Nothing
Notice how the variable FormData now contains the form data as text. Then you parse this text and locate the start and length of each file, and use ADODB.Stream CopyTo method to extract the specific portion of the file and save it do disk.