Đọc file Excel:
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
Dim xlRange As Excel.Range = Nothing
xlApp = New Excel.Application
Dim List As New List(Of List(Of Object))
Try
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open("Đường dẫn file Excel")
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
xlWorkSheet = CType(xlWorkSheets("Tên Sheet"), Excel.Worksheet)
xlRange = CType(xlWorkSheet.UsedRange.CurrentRegion, Excel.Range)
Dim xlRow As Excel.Range = Nothing
Dim xlCell As Excel.Range = Nothing
For irow As Integer = 1 To xlRange.Rows.Count
xlRow = CType(xlRange.Rows(irow), Excel.Range)
Dim lstRow As New List(Of Object)
For icol As Integer = 1 To xlRow.Cells.Count
xlCell = CType(xlRange.Cells(irow, icol), Excel.Range)
lstRow.Add(xlCell.Value)
Next
List.Add(lstRow)
Next
releaseObject(xlCell)
releaseObject(xlRow)
releaseObject(xlRange)
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlWorkSheets)
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlWorkBooks)
releaseObject(xlApp)
Catch
MsgBox("Lỗi!")
End Try
Với releaseObject được khai báo như sau:
Public Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
obj = Nothing
Catch ex As System.Exception
System.Diagnostics.Debug.Print(ex.ToString())
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
********************************************
Ghi file Excel:
Dim oldCI As System.Globalization.CultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US")
Dim xlApp As Object
xlApp = CreateObject("Excel.Application")
Dim xlWorkbook As Object = xlApp.Workbooks.Open("Đường dẫn file Excel")
Dim xlWorkSheet As Object = xlWorkbook.Worksheets(1) ' 1 là thứ tự của Sheet
' Set value
xlWorkSheet.Range("D5").Value = "Nội dung"
xlWorkbook.Save()
xlWorkbook.Close()
xlApp.Quit()
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
Không có nhận xét nào:
Đăng nhận xét