saving Textbox data to excel in vb.net - vb.net

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)

Related

Changing SaveFileDialog behaviour with filters

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

How Do I Use the Excel Function LoadPicture() from a Windows Form Application

I have a Windows Form application that my company uses to access all it's reports. Most of the reports are given to the user in an Excel sheet that is created at run-time either from scratch or an Excel Template. This has been working fine for everything up until now. The problem I am running into now is that I need to load an ImageBox on the Excel Template with an image saved on the drive. I have the filepath of the image (this will change each time this run). The only way I have found to be able to set the picture property of the ImageBox is like this...
Dim FileStr As String = "C:\Folder\ImageFile.jpg"
xlWorksheet.ImageName.Picture = LoadPicture(FileStr)
The problem is I can't figure out how to call the LoadPicture() function from within the windows form. I know I could create an Excel Module at run-time that call the LoadPicture() then delete it, but i just figured there had to be a better way? Hoping someone out there has suggestions. Thanks.
Edit:- Here is an example of the code I am Using to Open The Excel Sheet
Imports ExcelVB = Microsoft.Office.Interop.Excel
Imports ad = GartnerInterface.AdminClass.AdminTools
Imports xl = GartnerInterface.AdminClass.XlHelp
Public Class TestClass
Public Shared Sub NewSub()
Dim xlApp As ExcelVB.Application
Dim xlWorkbook As ExcelVB.Workbook
Dim xlWorksheet As ExcelVB.Worksheet
Dim TestSht As String
TestSht = "H:\Josh\ExcelTest.xlsm"
xlApp = CreateObject("Excel.Application")
xlWorkbook = xlApp.Workbooks.Add(TestSht)
xlApp.DisplayAlerts = False
xlApp.Visible = True
xlWorksheet = xlApp.Sheets("Sheet1")
Dim FileStr As String = "H:\12117\12117_Original.png"
'xlWorksheet.RFQImg.Picture = LoadPicture(FileStr)
End Sub
End Class
Now that I'm looking at the code, you would likely need the .AddPicture method
At the bottom of this code, you would need something like the following:
Dim FileStr As String = "H:\12117\12117_Original.png"
xlWorksheet.Shapes.AddPicture(FileStr, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45)
Taken from,
https://msdn.microsoft.com/en-us/library/office/ff198302.aspx
OR, if you have a template where the image is already named "test"
Dim FileStr As String = "H:\12117\12117_Original.png"
Dim imgName as String = "test"
For Each myShape In xlWorksheet.Shapes
If myShape.Name = imgName then
cTop = myShape.ShapeRange.Top 'we must save the values here
cLeft = myShape.ShapeRange.Left
cHeight = myShape.ShapeRange.Height
cWidth = myShape.ShapeRange.Width
myShape.delete
Exit For
end if
next
xlWorksheet.Shapes.AddPicture(FileStr, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, cLeft, cTop, cWidth, cHeight)
An example, with user interaction, I borrowed from

VB.net manage opened excel file on the fly

In my current project, i need to modify an excel file that is already opened. That mean, i need to see the change in the excel file whenever i modify it.
Since opened file is locked and vb cannot access that file, my solution is to open another excel file, modify its content and then copy to the original file using excel vba, as excel vba can be used to copy data between opening sheets.
Here is the vb code in my other excel file (called TTHT.xlsm):
Private Sub Worksheet_CHANGE(ByVal Target As Range)
Application.ScreenUpdating = False
If Sheet1.[B5].Value = "#" Then
Application.DisplayAlerts = False
With Workbooks.Open(ThisWorkbook.Path & "\PCN.xlsm")
With ThisWorkbook.Sheets("TTHT").[B5]
.Parent.Range("B4").Copy
Sheets("PCN").[B4].PasteSpecial 7
End With
End With
Application.DisplayAlerts = True
End If
End Sub
Runs fine between my 2 opening excel file ( that TTHT one and PCN.xlsm ).
Now all I need to do, is to fill the data into TTHT, and put a "#" into B5 by my code. I think it will work, but it's not..
Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdate.Click
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
oBook = oExcel.Workbooks.Open(TTHTPath)
oSheet = oBook.Worksheets("TTHT")
oSheet.Range("B4").Value = txtValue_Needed.text
oSheet.Range("B5").Value = "#"
oBook.Save()
'System.Diagnostics.Process.Start(DuongDanPhieuCongNghe)
oSheet = Nothing
oBook.Close()
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
End Sub
Result is, if i open the PCN file and click button, it won't change. If I close the PCN and click button, it will change..
But i need to see the change on the fly, not by close and reopen each time i need to update.
Can someone shed me some light, as to how, or which function ... either vba or vb.net, should i use ?
If the file is already opened and has focus then you can try looking it up in the running objects table.
Dim ExcelApplication As Excel.Application
ExcelApplication = GetObject("C:\Folder\ExcelWorkbook.xls")
Then you can just make your modifications on the instance which you referenced while trying to avoid disrupting the user.
The getobject() function is great; here's a link.
https://msdn.microsoft.com/en-us/library/e9waz863(v=vs.71).aspx

Vb.net to insert txt.file into template Excel

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.

Write to Excel Object

I am trying to write a code that exports data to excel after user prompted actions.
Basically, I have been able to export to Excel successfully, but the 2nd instance I want to write to a new tab instead of a new Excel application.
oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(3)
oSheet.Delete()
oSheet = oBook.Worksheets(2)
oSheet.Delete()
oSheet = oBook.Worksheets(1)
oSheet.Name = "Run " & Counter
At this point, the user will press a button, making Excel no longer active.
So when I want to write more data to a new sheet, the Object commands do not
'work unless I repeat code exactly.
I tried:
Counter +=1
'For the first instance
If Counter = 1 Then
oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(3)
oSheet.Delete()
oSheet = oBook.Worksheets(2)
oSheet.Delete()
oSheet = oBook.Worksheets(1)
oSheet.Name = "Run " & Counter
Else
'For every instance after that the user wants to do another run
oExcel.ActivateObject(Excel.Application)
oBook = oExcel.Workbooks(1)
oSheet = oBook.Worksheets.Add
oSheet.Name = "Run " & Counter
End If
I have been looking for days and am getting very frustrated. I do not know how to reference back to the open excel in order to continue to writing data ... after the user has pressed a button on the VB form confirming they want to do another run.
To get a reference to an already-running instance of excel you can use GetObject.
Eg:
' Test to see if a copy of Excel is already running.
Private Sub testExcelRunning()
On Error Resume Next
' GetObject called without the first argument returns a
' reference to an instance of the application. If the
' application is not already running, an error occurs.
Dim excelObj As Object = GetObject(, "Excel.Application")
If Err.Number = 0 Then
MsgBox("Excel is running")
Else
MsgBox("Excel is not running")
End If
Err.Clear()
excelObj = Nothing
End Sub
http://msdn.microsoft.com/en-us/library/e9waz863(v=vs.90).aspx
If Excel is not already running you can start a new instance using CreateObject.
I used to write VBA, but I was taught to get out of the habit of using CreateObject. you could also use a boolean just as well, but i imagine thats just preference. You should create the excel object outside the loop, hold reference at class level once its assigned. you then use the loop to solely assign the next sheets and add values. Keeping the dimension at class level means you do not need to get rid of the object immediately, because there is possibility the user might still need to use the reference.
Public Class Form1
Dim firstRun As Boolean = True
Dim xlApp As New Excel.Application
Dim xlWb As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'set up us some excel
xlApp.Visible = True
xlApp.SheetsInNewWorkbook = 1
xlWb = xlApp.Workbooks.Add
'imaginary loop
For i = 0 To 5
Dim msgResponse = MessageBox.Show("Do you want to loop?", "Keep Looping?", MessageBoxButtons.YesNo)
If msgResponse = Windows.Forms.DialogResult.No Then Exit For
If firstRun Then
xlSheet = xlWb.Sheets(1)
firstRun = False
Else
xlWb.Activate()
xlSheet = xlWb.Sheets.Add(After:=xlWb.Sheets(xlWb.Sheets.Count))
End If
xlSheet.Name = "TEST" & i
xlSheet.Range("A1").Value = "Some Data"
Next i
End Sub
End Class
You will need to make sure that you clean up your references once you are certain the user is done with the sheet.