วันเสาร์ที่ 9 เมษายน พ.ศ. 2554

การ Import Excel แบบเลือกจุดได้

Option Explicit On
'Option Strict On
Imports Microsoft.Office.Interop
Imports System.Object
Imports System.Exception
Imports System.SystemException
Imports System.Runtime.InteropServices.ExternalException
Imports System.Runtime.InteropServices.COMException

Public Class Test_Import_Excel_V2

Dim sFilePath, sFileName As String
Dim sSlash As Single
Dim myPath As String

Private Sub Test_Import_Excel_V2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'B a s s i e
End Sub

Private Sub export_to_excel()
OpenLgExcel()
Dim xlAPP As Excel.Application
Dim xlWB As Excel.Workbook
Dim XlWs As Excel.Worksheet

xlAPP = CreateObject("Excel.Application")
'##########################################################################################
'EX
'xlWB = xlAPP.Workbooks.Open(Application.StartupPath & "\Template\" & "Invoice.xls"))
xlWB = xlAPP.Workbooks.Open(myPath)
'##########################################################################################
'EX
'XlWs = xlWB.Sheets("Invoice")
'XlWs = xlWB.Sheets(2)
XlWs = xlWB.Sheets(2)
'##########################################################################################

TextBox2.Text = XlWs.Range("D2").Value

xlAPP.Visible = True
xlAPP.Workbooks.Close()
xlAPP.Quit()
XlWs = Nothing
xlWB = Nothing
xlAPP = Nothing
CloseLgExcel()
End Sub

Public Sub OpenLgExcel()
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
End Sub

Public Sub CloseLgExcel()
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("th-TH")
kill_process_Excel()
End Sub

Public Sub kill_process_Excel()
Try
Process.GetProcessesByName("EXCEL")(0).Kill()
Catch ex As Exception
End Try
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
With OpenFileDialog1
.Title = "Import Sage CSV file"
.InitialDirectory = "C:\Documents and Settings\htran\My Documents\vbnet\Welcome"
.Filter = "File (*.xls;*.csv;*.txt)|*.xls;*.csv;*.txt|All files (*.*)|*.*"

.ShowDialog()

sSlash = InStrRev(.FileName, "\")
sFilePath = Mid(.FileName, 1, sSlash)
sFileName = Mid(.FileName, sSlash + 1, Len(.FileName))
TextBox1.Text = .FileName
End With

myPath = sFilePath & sFileName
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
export_to_excel()
End Sub

End Class

ไม่มีความคิดเห็น:

แสดงความคิดเห็น