I have to export, under pressure of a button, some data in different extensions. To do this, I provided a SaveFileDialog, but depending on the filter (and so the output file extension), I have to write data with a different process:
if I have to export it as .txt or .csv, I have to use writer
otherwise if I have to export it as .xlsx, .xls or .ods I have to use NPOI
I provided the code both for writer and NPOI and they work singularly. If I try to put them together, .txt and .csv works, but for .xlsx, it exports a corrupted file.
This is the code I'm using:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt|CSV Files (*.csv*)|*.csv|Excel 2010 Workbook (*.xlsx*)|*.xlsx|Excel 2000 Workbook (*.xls*)|*.xls|OpenOffice Spreadsheet (*.ods*)|*.ods"
SaveFileDialog1.CheckFileExists = False
Dim t As Integer
t = CInt(Form10.Label13.Text)
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
If SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt|CSV Files (*.csv*)|*.csv|" Then
Using writer = New StreamWriter(SaveFileDialog1.FileName)
For Each o As Object In Form10.ListBox2.Items
writer.WriteLine(o)
Next
End Using
End If
End If
If SaveFileDialog1.Filter = "Excel 2010 Workbook (*.xlsx*)|*.xlsx|Excel 2000 Workbook (*.xls*)|*.xls|OpenOffice Spreadsheet (*.ods*)|*.ods|" Then
Dim fs As New FileStream(SaveFileDialog1.FileName, FileMode.Create, FileAccess.Write)
Dim workbook As IWorkbook = New XSSFWorkbook()
Dim worksheet As ISheet = workbook.CreateSheet()
Dim ich As ICreationHelper = workbook.GetCreationHelper()
Dim rows As New List(Of IRow)
Dim rowz As IRow = worksheet.CreateRow(0)
rowz.CreateCell(0).SetCellValue(ich.CreateRichTextString("Time [s]"))
rowz.CreateCell(1).SetCellValue(ich.CreateRichTextString("HRR [kW]"))
For i As Integer = 1 To t
Dim row As IRow = worksheet.CreateRow(i)
row.CreateCell(0).SetCellValue(CDbl(Form10.ListBox1.Items(i)))
row.CreateCell(1).SetCellValue(CDbl(Form10.ListBox2.Items(i)))
rows.Add(row)
Next i
workbook.Write(fs)
fs.Close()
End If
End If
End Sub
I'd like to know if the "if loop" is set properly for filters. Thanks all are gonna answer me. Best regards.
Just get the file path selected by the user and check its extension, e.g.
Select Case Path.GetExtension(SaveFileDialog1.FileName)
Case ".txt", ".csv"
'...
Case ".xlsx", ".xls", ".ods"
'...
End Select
Related
I need help with saving user entered data (textbox) to an excel file. The excel file should be created on desktop automatically. I can add one textbox to excel but not multiple. If possible can you give code on being able to open the same file when btnopen is clicked, thank you!
my code right now for save button.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
SaveFileDialog.Filter = "CSV Files (*.csv*)|*.csv"
If SaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog.FileName, txtBMI.Text, True)
End If
table.Rows.Add(DateTimePicker1.Text, txtBMI.Text, txtHeight.Text, txtWeight.Text)
DataGridView1.DataSource = table
End Sub
http://i.stack.imgur.com/H73M8.jpg
http://i.stack.imgur.com/Rjtjw.jpg
I think you need to use a supported library of creating Excel file and not to do it with file.create as you did.
You can use Microsoft Excel 12.0 Object Library and add a refernce to the bin folder or other dll of working with Excel instance.
Dim xlApp As Excel.Application = New
Microsoft.Office.Interop.Excel.Application()
You can see it here -
http://vb.net-informations.com/excel-2007/vb.net_excel_2007_create_file.htm
Add first the Microsoft Excel 12.0 Object Library via
Project>Properties>References>Add>COM>Type Libraries>Microsoft Excel 12.0 Object Library
Add releaseObject function (To release the excel file in the app):
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
After adding, declare the necessary variables so that it's easier to control the excel file:
Dim appXL As Excel.Application
Dim wbXl As Excel.Workbook
Dim shXL As Excel.Worksheet
Dim raXL As Excel.Range
' Start Excel and get Application object.
appXL = CreateObject("Excel.Application")
' Add a new workbook.
wbXl = appXL.Workbooks.Add
shXL = wbXl.ActiveSheet
shXL.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape
shXL.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA3
appXL.Visible = False
Add the headers with bold text:
With shXL.Range("A1", "D1")
.Font.Bold = True
End With
shXL.Cells(1,1) = "Date"
shXL.Cells(1,2) = "Height"
shXL.Cells(1,3) = "Weight"
shXL.Cells(1,4) = "BMI"
shXL.Cells(2,1) = DateTimePicker1.Text
shXL.Cells(2,2) = txtHeight.Text
shXL.Cells(2,3) = txtWeight.Text
shXL.Cells(2,4) = txtBMI.Text
Next, open the excel file.
appXL.Visible = True
appXL.UserControl = True
shXL.SaveAs("C:\Book1.xml")
raXL = Nothing
shXL = Nothing
wbXl = Nothing
appXL = Nothing
releaseObject(shXL)
releaseObject(wbXl)
releaseObject(appXL)
I've been struggling with a minor project, yet it's supposed to be easy. I have a windows form app in vba to insert values into a excel file.
It used to work in my company cause we had just a "couple" of data to enter. But now we are using txt files to gather the data to insert them in the excel file..
My problem is that we can't use macros anymore because there's always someone that changes something in the code.
My code WAS something like this:
Dim oApp As Excel.Application
Try
oApp = DirectCast(CreateObject("Excel.Application"), Excel.Application)
oApp.Workbooks.OpenText(Filename:=TextBox1.Text, _
Origin:=Excel.XlPlatform.xlMSDOS, _
DataType:=Excel.XlTextParsingType.xlDelimited, _
Comma:=False, Semicolon:=True, _
StartRow:=1)
oApp.Visible = True
oApp.Workbooks.Item(TextBox4.Text).SaveAs(Filename:=TextBox2.Text, _
FileFormat:=Excel.XlFileFormat.xlWorkbookNormal)
oApp.Workbooks.Item(TextBox3.Text).Close(SaveChanges:=False)
'Quit Excel
oApp.Quit()
oApp = Nothing
MessageBox.Show("Success.", "Success!", MessageBoxButtons.OK)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK)
End Try
NOW i want to use a template Excel, and insert the data in sheet1, cause sheet2 has all the graphs and stuff..
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
xlWorkBook = xlApp.Workbooks.Open(TextBox2.Text)
xlApp.Visible = True
xlWorkSheet = xlWorkBook.Sheets("data")
**With xlWorkSheet
'~~> Directly type the values that we want
.Range("A1").Value = "1"
.Range("A2").Value = "2"
End With**
End Sub
and i have no idea how to implement that. i don't know how to take the txt file and "place it" in sheet1..
Thank you all!
To insert a text file line by line into excel.
Dim inFile as string() = file.ReadAllLines("yourFileName")
xlWorkBook = xlApp.Workbooks.Open(TextBox2.Text)
xlApp.Visible = True
xlWorkSheet = xlWorkBook.Sheets("data")
for x as integer = 0 to inFile.length - 1
dim splitLine as String() = infile(x).split(";"c)
For y as integer = 0 to splitLine.length - 1
xlWorkSheet.rows(x + 1).Cells(y + 1).value = splitLine(y)
Next
Next
if you just want to attach the file with an icon showing then I would use this.
xlWorkSheet.Shapes.AddOLEObject("Word.Document.8", "YourfilePath", False, False)
I believe should work.
I'm new in VB.NET. I want to export Excel from VB.NET, and I'm using EPPlus for my project.
What are the four parameters of ws.cells() in this code?
Code:
Imports OfficeOpenXml
Imports OfficeOpenXml.Style
Imports System.IO
Public Class excelExport
Private Access As New DBControl
Public Sub myReport()
Dim saveDialog As New SaveFileDialog
saveDialog.Filter = "Excel File (*.xlsx)|*.xlsx"
saveDialog.FilterIndex = 1
If saveDialog.ShowDialog() = DialogResult.OK Then
Try
Dim file As FileInfo = New FileInfo(saveDialog.FileName)
' Ensures we create a new workbook
If (file.Exists) Then
file.Delete()
End If
Dim pck As ExcelPackage = New ExcelPackage(file)
' Add a new worksheet to the empty workbook
Dim ws As ExcelWorksheet = pck.Workbook.Worksheets.Add("Sheet1")
' Load data from DataTable to the worksheet
ws.Cells("A1").Value = "new"
ws.Cells.AutoFitColumns()
' Add some styling
Dim rng As ExcelRange = ws.Cells(1, 1, 1, 10) '<---------- This code
rng.Style.Font.Bold = True
rng.Style.Fill.PatternType = ExcelFillStyle.Solid
rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189))
rng.Style.Font.Color.SetColor(System.Drawing.Color.White)
' Save the new workbook
pck.Save()
MessageBox.Show(String.Format("Excel file {0} generated successfully.", file.Name))
Catch ex As Exception
MessageBox.Show("Failed to export to Excel. Original error: " + ex.Message)
End Try
End If
End Sub
End Class
Your first question is mainly asking for an opinion, which is not what this site is for. For what it is worth, I have found EPPlus useful for creating Excel files.
The answer to your second question is that the four arguments in the Cells method are:
The number of the first row to be included in the Range.
The number of the first column to be included in the Range.
The number of the last row to be included in the Range.
The number of the last column to be included in the Range.
Using VBA. My script moves a file into a directory. If that filename already exists in the target directory, I want the user to be prompted to rename the source file (the one that's being moved) before the move is executed.
Because I want the user to know what other files are in the directory already (so they don't choose the name of another file that's already there), my idea is to open a FileDialog box listing the contents of the directory, so that the user can use the FileDialog box's native renaming capability. Then I'll loop that FileDialog until the source file and target file names are no longer the same.
Here's some sample code:
Sub testMoveFile()
Dim fso As FileSystemObject
Dim file1 As File
Dim file2 As File
Dim dialog As FileDialog
Set fso = New FileSystemObject
fso.CreateFolder "c:\dir1"
fso.CreateFolder "c:\dir2"
fso.CreateTextFile "c:\dir1\test.txt"
fso.CreateTextFile "c:\dir2\test.txt"
Set file1 = fso.GetFile("c:\dir1\test.txt")
Set file2 = fso.GetFile("c:\dir2\test.txt")
Set dialog = Application.FileDialog(msoFileDialogOpen)
While file1.Name = file2.Name
dialog.InitialFileName = fso.GetParentFolderName(file2.Path)
If dialog.Show = 0 Then
Exit Sub
End If
Wend
file1.Move "c:\dir2\" & file1.Name
End Sub
But when I rename file2 and click 'OK', I get an error:
Run-time error '53': File not found
and then going into the debugger shows that the value of file2.name is <File not found>.
I'm not sure what's happening here--is the object reference being lost once the file's renamed? Is there an easier way to let the user rename from a dialog that shows all files in the target directory? I'd also like to provide a default new name for the file, but I can't see how I'd do that using this method.
edit: at this point I'm looking into making a UserForm with a listbox that gets populated w/ the relevant filenames, and an input box with a default value for entering the new name. Still not sure how to hold onto the object reference once the file gets renamed, though.
Here's a sample of using Application.FileDialog to return a filename that the user selected. Maybe it will help, as it demonstrates getting the value the user provided.
EDIT: Modified to be a "Save As" dialog instead of "File Open" dialog.
Sub TestFileDialog()
Dim Dlg As FileDialog
Set Dlg = Application.FileDialog(msoFileDialogSaveAs)
Dlg.InitialFileName = "D:\Temp\Testing.txt" ' Set suggested name for user
' This could be your "File2"
If Dlg.Show = -1 Then
Dim s As String
s = Dlg.SelectedItems.Item(1) ` Note that this is for single-selections!
Else
s = "No selection"
End If
MsgBox s
End Sub
Edit two: Based on comments, I cobbled together a sample that appears to do exactly what you want. You'll need to modify the variable assignments, of course, unless you're wanting to copy the same file from "D:\Temp" to "D:\Temp\Backup" over and over. :)
Sub TestFileMove()
Dim fso As FileSystemObject
Dim SourceFolder As String
Dim DestFolder As String
Dim SourceFile As String
Dim DestFile As String
Set fso = New FileSystemObject
SourceFolder = "D:\Temp\"
DestFolder = "D:\Temp\Backup\"
SourceFile = "test.txt"
Set InFile = fso.GetFile(SourceFolder & SourceFile)
DestFile = DestFolder & SourceFile
If fso.FileExists(DestFile) Then
Dim Dlg As FileDialog
Set Dlg = Application.FileDialog(msoFileDialogSaveAs)
Dlg.InitialFileName = DestFile
Do While True
If Dlg.Show = 0 Then
Exit Sub
End If
DestFile = Dlg.Item
If Not fso.FileExists(DestFile) Then
Exit Do
End If
Loop
End If
InFile.Move DestFile
End Sub
Here's some really quick code that I knocked up but basically looks at it from a different angle. You could put a combobox on a userform and get it to list the items as the user types. Not pretty, but it's a start for you to make more robust. I have hardcoded the directory c:\ here, but this could come from a text box
Private Sub ComboBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)
Dim varListing() As Variant
Dim strFilename As String
Dim strFilePart As String
Dim intFiles As Integer
ComboBox1.MatchEntry = fmMatchEntryNone
strFilePart = ComboBox1.Value
strFilename = Dir("C:\" & strFilePart & "*.*", vbDirectory)
Do While strFilename <> ""
intFiles = intFiles + 1
ReDim Preserve varListing(1 To intFiles)
varListing(intFiles) = strFilename
strFilename = Dir()
Loop
On Error Resume Next
ComboBox1.List() = varListing
On Error GoTo 0
ComboBox1.DropDown
End Sub
Hope this helps. On error resume next is not the best thing to do but in this example stops it erroring if the variant has no files
I have this script that I'd like to in addition save as a xls file, also save as a .txt in the same directory, or even a different one. Can I get some guidance here?
Imports System.IO
Module Module1
Private Property fs As Object
Private Property BaseName As Object
Private Property FullTargetPath As Object
Sub Main()
Dim targetfolder As String = "C:\TEST"
Dim sourcefolder As String = "\\10.97.8.16\c$\Checks\XMLFiles"
Dim Searchpattern As String = String.Format("{0:MM-dd-yyyy}*.xml", Date.Today)
Dim todaysfiles() As String = Directory.GetFiles(sourcefolder, Searchpattern)
Dim xlApp, xlWkb
xlApp = CreateObject("excel.application")
fs = CreateObject("Scripting.FileSystemObject")
Const xlnormal = 1
'Extra Dims
'Hide Excel
xlApp.Visible = False
For Each file As String In todaysfiles
' Excel stuff... '
Dim fileName As String = IO.Path.GetFileNameWithoutExtension(file)
' Concatenate full path. Extension will be automatically added by Excel. '
Dim fullTargetPath = IO.Path.Combine(targetfolder, fileName)
'Process each file in SourceFolder
' For Each file In fs.GetFolder(SourceFolder).files
'Open file in SourceFolder
xlWkb = xlApp.Workbooks.Open(file)
'Get Filename
BaseName = fs.getbasename(file)
'Concatenate full path. Extension will be automatically added by Excel
fullTargetPath = targetfolder & "\" & BaseName
'Save as XLS file into TargetFolder
xlWkb.SaveAs(fullTargetPath, xlnormal)
'Close the file after its done
xlWkb.close()
Next
xlWkb = Nothing
xlApp = Nothing
fs = Nothing
' MsgBox("Thank you. Currently the Date is: " & Date.Today & " people like to eat chicken Every " & Date.Today.Ticks & " minutes.")
'This is for extra code below
End Sub
End Module
Pretty much exactly as you are doing now, but change the format in from xlnormal to xltext.
xlWkb.SaveAs(fullTargetPath, xltext)
When researching something like this I like to look around the object browser under vba editor. Look up Workbook object in this case and then the SaveAs sub to get the definition (parameters and types) then you can click on the parameter you want more information on and look it up from the help menu. I say that from memory I have not played with excel macros in years. Good luck!
Why can't you call
xlWb.SaveAs(fullTargetPath, XlFileFormat.xlTextWindows)
or with any other xlFileFormat type?